Extract variables from string math expression

前端 未结 3 1524
时光取名叫无心
时光取名叫无心 2020-12-11 11:14

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

List Variables = new List();
str         


        
相关标签:
3条回答
  • 2020-12-11 11:54

    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.

    0 讨论(0)
  • 2020-12-11 12:10

    I like using the Shunting-yard algorithm: http://en.wikipedia.org/wiki/Shunting-yard_algorithm It makes eval easy.

    0 讨论(0)
  • 2020-12-11 12:16

    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;

    0 讨论(0)
提交回复
热议问题