Mathematical Expression Evaluation from string in C# using Stack


Mathematical string expression can be evaluate in c# using build in
public static double Evaluate(String input)
        {
            String expression = "(" + input + ")";
            Stack<String> operators = new Stack<String>();
            Stack<Double> values = new Stack<Double>();

            for (int i = 0; i < expression.Length; i++)
            {
                String str = expression.Substring(i, 1);
                String prevStr = string.Empty;
                if (i > 1)
                    prevStr = expression.Substring(i - 1, 1);
                if (str.Equals("(")) { }
                else if (str.Equals("+")) operators.Push(str);
                else if (str.Equals("-")) operators.Push(str);
                else if (str.Equals("*")) operators.Push(str);
                else if (str.Equals("/")) operators.Push(str);
                else if (str.Equals("sqrt")) operators.Push(str);
                else if (str.Equals(")"))
                {
                    int count = operators.Count;
                    while (count > 0)
                    {
                        String op = operators.Pop();
                        double v = values.Pop();
                        if (op.Equals("+")) v = values.Pop() + v;
                        else if (op.Equals("-")) v = values.Pop() - v;
                        else if (op.Equals("*")) v = values.Pop() * v;
                        else if (op.Equals("/")) v = values.Pop() / v;
                        else if (op.Equals("sqrt")) v = Math.Sqrt(v);
                        values.Push(v);

                        count--;
                    }
                }
                else
                {
                    if (IsDigit(prevStr))
                    {
                        double val = values.Pop();
                        values.Push(val * 10 + Double.Parse(str));
                    }
                    else

                        values.Push(Double.Parse(str));
                }
            }
            return values.Pop();
        }

        private static bool IsDigit(string str)
        {
            int temp;
            if (int.TryParse(str, out temp))
                return true;
            else
                return false;
        }

Comments

Popular posts from this blog

Deploying MVC3 R2 Applications in Windows Shared Hosting Environment