从字符串中添加整数

时间:2014-07-24 14:49:19

标签: c#

我有一个像str =" 4 + 6 * 30&#34 ;; 我必须使用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;

有没有更好的方法呢?

1 个答案:

答案 0 :(得分:4)

你可以这么简单地做一下(有点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