-3

Say a program receives an input string "8*10+6/2" and should output 83, in this case. how to handle the operator?

I can chop the string into individual strings, then detect whether it is a number or operator. If it is an operator I can convert it to int. But I have no idea how to handle the operator so that the calculation works.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
John Ryann
  • 2,283
  • 11
  • 43
  • 60
  • Have you tried anything? – Pierre-Luc Pineault Sep 13 '13 at 22:33
  • Regexes and String splitting are your friends :) – Jhon Sep 13 '13 at 22:34
  • 2
    Sounds like a good candidate for a [parser](https://gppg.codeplex.com/). – Arian Motamedi Sep 13 '13 at 22:34
  • @JhonAlx: regex and string splitting will definitely not be your friend here. Writing (or searching for) a parser will be an easier way to handle things. – Jeroen Vannevel Sep 13 '13 at 22:39
  • @JeroenVannevel I said it because i worked on something like [this](https://github.com/JhonAlx/tc-solutions/blob/master/Main/src/SimpleCalculator.java) training in TopCoder. My solution does not have operator precedence analysis because of the problem statement, but with some work it would work :) – Jhon Sep 13 '13 at 22:46

1 Answers1

7

You could use the DataTable.Compute-"trick":

double result = (double)new DataTable().Compute("8*10+6/2", null);

The following arithmetic operators are supported in expressions:

+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulus)

More informations in: DataColumn.Expression at Expression Syntax.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • John Ryann, @Tim Schmelter's answer is what you'd use in real life, but for school they might want you to do some trickery with `if (string.equals("/")){use division...} else if (str.equals("*")...`. It depends on whether this is an exercise from an intro to programming course or a C# language course. You could also try using char comparisons and a switch statement. The exact implementation is within your abilities. Good luck! :) – JaneGoodall Sep 13 '13 at 22:40
  • This answer saves the question. +1 – Jan Dörrenhaus Sep 13 '13 at 22:49