当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - adding Integers from string

问题描述:

I have a string like str = " 4+ 6 * 30";

I have to do an arithmatic operation on this using c#.

My solution to this problem is:

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;

Is there better way to do that?

网友答案:

You can do this very simply (a bit hackish...) like this:

string expression = "4 + 6 * 5";

DataTable dt = new DataTable();
var result = dt.Compute(expression, "");

Console.WriteLine(result);//34

This also handles order of operations correctly like so:

string expression = "(4 + 6) * 5";

DataTable dt = new DataTable();
var result = dt.Compute(expression, "");

Console.WriteLine(result);//50
分享给朋友:
您可能感兴趣的文章:
随机阅读: