C# Equation and Formula Parser

C# Equation and Formula Parser

Developing an equation parser is a challenging task in programming world. You either have to use a stack to track prioritization of the operations or have to develop a recursive structure which is hard to maintain for the future use.

In this page, we will provide a stack solution written in c# to handle "Equation and Formula Parser" problem.

Here is the C# source code of an "Equation and Formula Parser" that is developed by my old friend Ahmed Yasin Koçulu.

void Main()
{
    string input = "2-(3*(2-7)+4+5)*7";
    System.Console.WriteLine(input + " = " + Calculate(input));
}

double Calculate(string input)
{   
    var list = Regex.Split(input, "([+*-/()])")
        .Where(x => !string.IsNullOrWhiteSpace(x));
    double result = 0;

    Stack numStack = new Stack();
    Stack opStack = new Stack();
    bool fetchNumber = true;
    foreach(var m in list)
    {
        if(m == "(")
        {
            opStack.Push(m);
        }
        else if(m == ")")
        {
            Walk(numStack, opStack, true);
        }
        else
        {
            if(fetchNumber)
            {
                double number = double.Parse(m.Trim());
                numStack.Push(number);
            }
            else
            {
                if(m == "+" || m == "-")
                    Walk(numStack, opStack);
                opStack.Push(m);
            }
            fetchNumber = !fetchNumber;
        }
    }
    Walk(numStack, opStack);
    result = numStack.Pop();
    return result;
}

void Walk(Stack numStack, Stack opStack, bool close = false)
{
    while(opStack.Count > 0 && numStack.Count > 1)
    {
        if(opStack.Peek() == "(")
        {
            if(close)
                opStack.Pop();
            break;
        }
        string operation = opStack.Pop();       
        double d2 = numStack.Pop();
        double d1 = numStack.Pop();
        double z1 = 0;
        switch(operation)
        {
            case "+": z1 = d1 + d2; break;
            case "-": z1 = d1 - d2; break;
            case "*": z1 = d1 * d2; break;
            case "/": z1 = d1 / d2; break;
        }
        numStack.Push(z1);
    }
}


C# Equation and Formula Parser
added 5 years 6 months ago

- C# Equation and Formula Parser