1

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?

16
  • 2
    What should the answer be? (4 + 6) * 5 = 50 or 4 + (6 * 5) = 34? This is a lot more complex than it might look on the surface. Commented Jul 24, 2014 at 14:51
  • 1
    This would be better asked on codereview.stackexchange.com Commented Jul 24, 2014 at 14:52
  • Take a look Is there a string math evaluator in .NET? and Math Parser .NET and muparser Commented Jul 24, 2014 at 14:53
  • 1
    @Jonny in the absence of parentheses, order of operations is used, not very complex at all, at least in that regard. Commented Jul 24, 2014 at 14:53
  • 2
    @Wobbles: But that's just the question - which order of operations should be applied? The one in which the operations are written? Or the one that is commonly applied (multiplication/division before addition/subtraction)? And the latter case is exactly where it gets complex, because the OP cannot just read the next operation and execute it step by step, but actually they need to build an expression tree and evaluate subtrees only when it is clear nothing more will be added. Commented Jul 24, 2014 at 15:11

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.