I would like to convert a string equation such as 10+20
or even use of numerous operators such as 10+20*5
into an answer such as 110 from a string equation.
I have currently tried looping through each char of the equation string and sorted the numbers and operators, however, I'm not able to get any further than this. Help would be much appreciated!
int calculateFromString(string equation) {
int numbers;
string operators;
// iterate through the equation string
for (int i = 0; i < equation.length(); i++) {
if (equation.charAt(i) >= '0' && equation.charAt(i) <= '9') {
numbers += int(equation.charAt(i));
}
if (equation.charAt(i) == '+' || equation.charAt(i) == '-' || equation.charAt(i) == '*' || equation.charAt(i) == '/') {
operators += equation.charAt(i);
}
}
return numbers;
}
My intended result would be:
calculateFromString("10+20*5")
= 110
I was able to get the operators from the string and store them into the operators string using:
if (equation.charAt(i) == '+' || equation.charAt(i) == '-' || equation.charAt(i) == '*' || equation.charAt(i) == '/') {
operators += equation.charAt(i);
}
However, I'm not sure how I can turn this data into an equation that can be calculated.