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 stringsstring[] withoutOperator = temp.Split('\t',' ','*' , '+');//Iterating stringsint 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
``````

Top