3

I'm trying to split a simple mathematics expression from it's parenthesis

For example : (8+(3(2+3)(4-1))) to separate in to little expressions like (2+3), (4-1), (3*5*3), and finally (8+45).

I tried looking at here Splitting an expression, but since it's in python, I don't know how to implement it in Java.

Can someone please help me..

Community
  • 1
  • 1
Grainier
  • 1,634
  • 2
  • 17
  • 30
  • 1
    If you just want to evaluate the expression, take a look at [this](http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form) and [this](http://stackoverflow.com/questions/1432245/java-parse-a-mathematical-expression-given-as-a-string-and-return-a-number) post – Rohit Jain Nov 07 '12 at 06:29
  • This isn't just 'split[ting] a simple mathematics expression from its parenthesis'. This is called 'parsing' and 'evaluation'. It's a lot more complicated than just 'splitting'. For example you would also need to be able to evaluate `(8+3(2+3)(4-1))` correctly even without the parentheses around the inner multiplications. – user207421 Nov 07 '12 at 06:50
  • possible duplicate of [Equation (expression) parser with precedence?](http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence) – user207421 Nov 07 '12 at 06:52

3 Answers3

3

Do you actually have to "Split" it or do you just need to evaluate it? It's easier to evaluate it directly.

This was my answer to that...

Parsing an arithmetic expression and building a tree from it in Java

Community
  • 1
  • 1
Bill K
  • 62,186
  • 18
  • 105
  • 157
3

I think dijkstra's shunting yard algorithm might help you, its purpose is to solve expressions that are in infix notation. You can take intermediate results to get the expressions you are looking for.

http://en.wikipedia.org/wiki/Shunting-yard_algorithm

C example code is included, this should help you since it's similar to Java.

0

Just a suggestion use arithmatic expression tree to solve this. I've done this using C#, if you are interested I can give the method

Zarco
  • 177
  • 2
  • 3
  • 13