Hi, i need a function that gets a string and calculates it and then returns a integer.
For eksample if the string is "5+3" Then the function should return 8.
How can I make this. I guess someone has already done something like this before. Any tips, or codeexamples??
Thanks for help.
PGD Staff / Administrator
In that case... I would suggest you read a couple of bits. The first discusses Reverse Polish Notation.
Reverse polish notation (RPN) is a means of representing expressions in a way that is friendly for stack based languages (Forth for example).
2+3 is represented as a sequence of operations such as push(2), push(3) add. Where 2 is pushed onto a stack, 3 is pushed onto a stack and the operator add pops two items from the stack and adds them together before pushing the answer back onto the stack. It gets a little complicated when you start dealing with parenthesis, etc. But there is an algorithm called the Shunting Yard Algorithm which deals with converting an expression to RPN.
Once you've converted an expression, you should look at caching the RPN representation for it. This will save you having to convert it every time. And if you really want to get clever, you can look to pre-process constants and then re-use the optimised RPN.
For example, 2+3+4+5. Let's say this occurs in a loop that is executed a lot, converting it to RPN and then running it every time would be highly wasteful. It's always going to be 14. So instead of converting it to the RPN representation equivalent to push(2), push(3), add, push(4), add, push(5), add you could simply represent it as push(14).
I have used conversion of expressions and then storage of the RPN representation myself (many years ago, Turbo Pascal 7 on the PC side and BBC Basic on an Amstrad NC-100) and it worked a treat. I'm sure there will be other opinions about how to do this, but this is how I would approach it.
Use the shunting yard algorithm to convert the expression to the RPN representation and then produce a stack evaluator to 'run' the resulting RPN.
I hope this helps, if you have more questions obviously ask away
you can try to use cqparser
you need to register to download the file but it can calculate strings really fast so it is worth it
You can try CalcExpress its a very basic evaluation component, but hey! it's freeware with source code.