我写了一个简单的程序,将参数中的字符串拆分为数字、字母和运算符,但是我遇到了 23x+3=8
foreach (char x in args[i]){
if (char.IsNumber(x)){
inter[i] = Convert.ToInt32(x);
Console.WriteLine("{0} is a number ", x);
}
else if (char.IsLetter(x)){
apha[i] = x;
Console.WriteLine("{0} is a Letter ", x);
}
else if (char.IsSymbol(x)){
symbol[i] = x;
Console.WriteLine("{0} is a Symbol ", x);
}
我发现输出分为每个字符 2 和 3 我想要 23 作为一个整数。有没有办法把 2 个数字放在一起?
最佳答案
我会尝试以下方法
string equation = "25x+20=120";
// Guard against an empty input
if (String.IsNullOrWhiteSpace(equation))
throw new ArgumentException("No equation given!");
// Regex split
// Split is being applied on the mathematical operations
var result = Regex.Split(equation, @"([*+-/=])");
foreach (var item in result)
{
Console.WriteLine(item);
// TODO : Further operations
}
这将生成输出
25x
+
20
=
120
该过程使用正则表达式。 ([*+-/=])
将拆分指定的数学运算,()
将确保运算包含在结果拆分中,从而允许您重建操作树。
请参阅 System.Text.RegularExpressions 上的文档,您可以在 Regular Expression Language Reference 上看到更深入的引用。
关于c# - 分离 int 和 char 并生成整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997870/