Possible Duplicate:
C# – Parse Math Expression
C#, User defined formula
The equation will only use addition, subtraction, multiplication, division operators and will not use brackets. I didn’t think it would be so difficult, but I’ve been thinking about it for hours while trying different things and writing different ideas out.
I thought there might be some way by splitting the string on each of those characters and doing something with the output or by looping through the string character by character and coming up with something, but I’m not clever enough I guess.
Anyways, I’d love to hear other peoples’ ideas because I’m stumped. I don’t want to use a third-party library of some kind which is what everybody has suggested in old threads that I’ve been looking at.
For such simple equations it could be implemented with a split and two loops.
For a string like this:
"4+5*6/2-8"Split on operators, keeping them in the result:
Loop though the operators and calculate multiplication and division, putting the result back in the list:
Loop through the operators again and calculate addition and subtraction this time: