本文介绍了检测字符串中的十进制数字和字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个数学应用程序.如何在 c# 中检测字符串中的数字和字母.例如:
I am writing a mathematical application. How can I detect a number and alphabet in string in c#. For Example:
string a = "2x"; // input string
string b = a.Replace("2x","2*x"); // Replace string to add multiplaction sign between a number and variable
可以是整数或双精度数.
It could be an integer or double type number.
推荐答案
regex replace:
regex replace:
var math = new Regex(@"\d[a-zA-Z]");
var expr = "-2X-4Z-5Y";
string replaced = math.Replace(expr, m => String.Concat(m.Value[0], '*', m.Value[1]));
输出
-2*X-4*Z-5*Y
更新
如果系数和变量之间可以有圆括号,修改replace如下:
if there can be round brackets between coefficient and variable, change replaceas follows:
var math = new Regex(@"\d(\()*[a-zA-Z]");
var expr = "10+2(X+5(a+b))";
string replaced = math.Replace(expr,
m => String.Concat(m.Value[0], "*", m.Value.Substring(1)));
输出
10+2*(X+5*(a+b))
这篇关于检测字符串中的十进制数字和字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!