Search code examples
c#string-parsing

Parse string with arithmetic operation


I have a string of the following type:

"23 + 323 =" or "243 - 3 ="

So the format is: number + operator + number = equal.

And I also have an int which is the answer to that question.

How can I parse the string and check if the answer is correct?

Thank You, Miguel


Solution

  • Maybe using regular expressions you can do something like...

    String sExpression = "23 + 323 =";
    int nResult = 0;
    Match oMatch = Regex.Match(@"(\d+)\s*([+-*/])\s*(\d+)(\s*=)?")
    if(oMatch.Success)
    {
        int a = Convert.ToInt32(oMatch.Groups[1].Value);
        int b = Convert.ToInt32(oMatch.Groups[3].Value);
        switch(oMatch.Groups[2].Value)
        {
            case '+';
                nResult = a + b;
                break;
            case '-';
                nResult = a - b;
                break;
            case '*';
                nResult = a * b;
                break;
            case '/';
                nResult = a / b;
                break;
        }
    }
    

    and extend to your need.. (floats, other operators, validations, etc)