Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

c# - Extract variables from string math expression

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

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

1 Reply

0 votes
by (71.8m points)

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;


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...