Skip to main content
 首页 » 编程设计

c#之从字符串中添加整数

2024年02月06日23insus

我有一个像 str = "4+ 6 * 30"这样的字符串; 我必须使用 c# 对此进行算术运算。 我对这个问题的解决方案是:

string temp = " 4 + 6 * 5"; 
int firstNaum = 0; 
int secondNum = 0; 
int ThirdNum = 0; 
int finalResults = 0; 
 
//Spliting strings 
string[] withoutOperator = temp.Split('\t',' ','*' , '+'); 
 
//Iterating strings  
int counter = 0; 
foreach (var res in withoutOperator) 
{ 
    if (!string.IsNullOrEmpty(res) && counter ==1) 
    { 
        firstNaum = Convert.ToInt32(res); 
    } 
    if (!string.IsNullOrEmpty(res) && counter== 4) 
    { 
        secondNum = Convert.ToInt32(res); 
    } 
    if (!string.IsNullOrEmpty(res) && counter == 7) 
    { 
        ThirdNum = Convert.ToInt32(res); 
    } 
    counter += 1; 
} 
finalResults = firstNaum + secondNum * ThirdNum; 

有更好的方法吗?

请您参考如下方法:

您可以像这样非常简单地(有点 hackish...)做到这一点:

string expression = "4 + 6 * 5"; 
 
DataTable dt = new DataTable(); 
var result = dt.Compute(expression, ""); 
 
Console.WriteLine(result);//34 

这也像这样正确处理操作顺序:

string expression = "(4 + 6) * 5"; 
 
DataTable dt = new DataTable(); 
var result = dt.Compute(expression, ""); 
 
Console.WriteLine(result);//50