Is there a string math evaluator in .NET?

前端 未结 16 1433
长情又很酷
长情又很酷 2020-11-22 01:01

If I have a string with a valid math expression such as:

String s = \"1 + 2 * 7\";

Is there a built in library/function in .NET that will p

16条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 01:40

    A simple math parser is quite easy to build, and requires only a few lines of code:

    Take this flexible example:

    class RPN
    {
        public static double Parse( Stack strStk )
        {
            if (strStk == null || strStk.Count == 0 )
            {
                return 0;
            }
            Stack numStk = new Stack();
            double result = 0;
    
            Func op = null;
            while (strStk.Count > 0)
            {
                var s = strStk.Pop();
                switch (s)
                {
                    case "+":
                        op = ( b ) => { return numStk.Pop() + b; };
                        break;
                    case "-":
                        op = ( b ) => { return numStk.Pop() - b; };
                        break;
                    case "*":
                        op = ( b ) => { return numStk.Pop() * b; };
                        break;
                    case "/":
                        op = ( b ) => { return numStk.Pop() / b; };
                        break;
    
                    default:
                        double.TryParse(s, NumberStyles.Any, out result);
                        if (numStk.Count > 0)
                        {
                            result = op(result);
                        }
                        numStk.Push(result);
                        break;
                }
            }
            return result;
        }
    }
    
    ....
    var str = " 100.5 + 300.5 - 100 * 10 / 100";    
    str = Regex.Replace(str, @"\s", "", RegexOptions.Multiline);
    Stack strStk = new Stack(
         Regex.Split(str, @"([()*+\/-])", RegexOptions.Multiline).Reverse()
    );
    RPN.Parse(strStk);
    

    To enable precedence by bracketing a stack of stacks will suffice, such as archived by recursion. Anything between brackets is put on a new stack. Finally you can support math operations in a clean readable fashion by lambdas.

提交回复
热议问题