I am going to write an expression evaluator which only does addition and subtraction. I have a simple algorithm to do that; but, I have some implementation problems.
I considered an expression as (it is a String)
"(" <expression1> <operator> <expression2> ")"
Here is my algorithm
String evaluate( String expression )
if expression is digit
return expression
else if expression is "(" <expression1> <operator> <expression2> ")"
cut the brackets out of it
expression1 = evaluate( <expression1> )
operator = <operator>
expression2 = evaluate( <expression2> )
if operator is +
expression1 + expression2
else if operator is -
expression1 - expression2
My problem is parsing <expression1>
, <operator>
and <expression2>
from the expression. How can I do that?
Note: I'm not asking for a code. All I need is an idea to do that.