Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to extract variables from math expression using c#. I wrote this code and it works right:

List<string> Variables = new List<string>();
string temp = string.Empty;
Console.WriteLine("Please enter ur expression");
string Expression = Console.ReadLine().Trim();
int Index;
for (Index = 0; Index <= Expression.Length - 1; Index++)
{
    if (char.IsLetter(Expression[Index]))
    {
        temp = temp + Expression[Index];
    }
    else
    {
        if (temp.Length > 0)
        {
            Variables.Add(temp);
            temp = string.Empty;
        }
    }
}
if (temp.Length > 0)
{
    Variables.Add(temp);
}
foreach (string item in Variables)
{
    Console.WriteLine(item);
}
Console.ReadKey();

I have to detect SIN and COS from expression so I will remove SIN and COS from Variables.

  1. Is it good way ?
  2. IS it possible to do this with Regular expressions or better ways ?
  3. Does this code need refactoring ?

After extract I want replace variables with values from input and I will calculate the expression result.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
259 views
Welcome To Ask or Share your Answers For Others

1 Answer

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: automataImage

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;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...