Question

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

Was it helpful?

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)

OTHER TIPS

You want to split on equals then split on the operator. Then you can use some standard string processing techniques to do the operation and check it against the answer. There are probably far more efficient and/or cleaner solutions than this, this is simply the first one at my fingertips and since you didn't post any code it is what you get. Note that this also is not flexible. It only works when there are two operands and with the four primary arithmetic operators. Unless there's some requirement saying you don't use third party libraries I'd recommend using something like what's linked to in the comments. If you need to implement this in a more general sense (works with multiple operations like (x + y - z) * x ) then you have a lot more work cut out for you.

 string input = "23 + 323 = 346";

 string[] sides = input.Split('=');
 string[] operands;
 int answer = 0;

 if (sides.Length == 2)
 {
      if (sides[0].Contains('+'))
      {
          operands = sides[0].Split('+');
          operands[0].Trim();
          operands[1].Trim();
          answer = int.Parse(operands[0]) + int.Parse(operands[1]);
          // note if you're serious about error handling use tryparse to ensure the values are integers
          if (answer != int.Parse(sides[1].Trim()))
             // answer is wrong
      }
      else if (sides[0].Contains('-'))
      {
          // same logic
      }
 }
 else
      //input formatting error

As all of the comments to your question indicate, you need some kind of tokenizer, expression parser, and expression evaluator.

The tokenizer splits the source string into separate tokens, like numbers and operators.

The expression parser scans and syntactically parses the sequence of tokens, recognizing expressions and building some kind of parse tree (i.e., an abstract expression tree).

The expression evaluator then walks the nodes of the resulting expression tree, evaluating the binary and unary subexpressions. The result is the evaluation of the top-most node in the tree.

This is all quite a complex set of things to do, so (like the other comments state), you should try to find a library that someone has already written to do all this for you.

Actually it is not that different from parsing single arithmetic expression. Here you simply evaluate two of them (on both sides of equal sign) and then check the outcome.

Well, you can go "crazy", and parse not only = but >, >= too, which will give you more flexibility.

Because in arithmetic expression parenthesis should be legal (common sense), for example (5+2)*3 you should avoid struggle with regexes and alike approaches and go with parser.

Pick one you feel comfortable with, GOLD, ANTLR, Cocoa. My own parser (generator) -- NLT -- contains already arithmetic expression example. Add single rule for checking equality and you are ready to go.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top