-7

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

Konrad Kokosa
  • 16,563
  • 2
  • 36
  • 58
Miguel Moura
  • 36,732
  • 85
  • 259
  • 481
  • 4
    Look into [String.Split](http://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx). Convert the first and third tokens to ints, and switch on the operator in between. – Scott Mermelstein Dec 11 '13 at 17:42
  • See here: http://stackoverflow.com/a/3972939/426422 – Mike Cheel Dec 11 '13 at 17:44
  • [Look](http://weblogs.asp.net/pwelter34/archive/2007/05/05/calculator-net-calculator-that-evaluates-math-expressions.aspx) what I [found](http://www.codeproject.com/Articles/13335/C-Eval-Function)! – Brian Dec 11 '13 at 17:44

4 Answers4

3

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)

CaldasGSM
  • 3,032
  • 16
  • 26
  • I like your solution and want to use it, if instead of number I have a path to some file for calculations what should I put instead of "\d" in the Match statement? – Mahsa Apr 01 '15 at 19:12
  • how are you gonna to arithmetic operations on a file path? – CaldasGSM Apr 02 '15 at 11:28
  • Well that's the part I already took care of, it's a huge 3D matrix that I have divided it and I am using an xml file for that. Anyway that part is my least problem. I was thinking using your solution but instead reading bunch of characters for the path and Operand and integer value. I am writing the program in Scala. – Mahsa Apr 03 '15 at 15:28
  • well if you just want the tecnique, to parse some string .. you can modify the regular expression as you like but if you dont know how I sugest ready a bit about RX first http://www.regular-expressions.info/ – CaldasGSM Apr 04 '15 at 23:32
0

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
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
0

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.

David R Tribble
  • 11,918
  • 5
  • 42
  • 52
0

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.

greenoldman
  • 16,895
  • 26
  • 119
  • 185