Try sketching an automata that detects expressions.
After that the simplest way to implement an automata would be a switch..case with nested if..else.
I think it would be far easier than parsing the string the way you are right now.
Edit--
This is a very simple example, only for the sake of demonstration. suppose I want to detect expressions in the form of var1 + var2, the automata would look like this:
Image
Implementaion looks like this:
done = false;
state = start;
while(!done)
{
switch(state)
{
case start:
if(expression[i] > 'a' && expression[i] < 'z')
state = start;
else if(expression[i] == '+')
{
// seen first operand and waitng for second
// so we switch state
state = add;
}
break;
case add:
if(expression[i] > 'a' && expression[i] < 'z')
state = add;
else
done = true;
break;
}
}
Like I said this is very simple, your automata would be more complex with many more states and transitions. I've also not included actions here, but you could do actual addition after second operand is read which is after done = true;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…