I want to extract variables from math expression using c#. I wrote this code and it works right:
List Variables = new List();
str
If you want parse experssion yourself, your ways seems good, but it doesn't evaluate it, in this cases I prefer to use previous wrote parsers like NCalc, instead of creating the wheal, but if this is a homework and you just want to find variables, your way can be optimized by for example doing temp += Expression[Index];
, Also may be using Experssion.Split(...
works better in this case. and if you want parse it yourself you can use shutting yard algorithm.
I like using the Shunting-yard algorithm: http://en.wikipedia.org/wiki/Shunting-yard_algorithm It makes eval easy.
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;