Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string expression to boolean logic - C#

I want to convert a string expression to a real boolean expression.

The expression below will be an input (string):

"(!A && B && C) || (A && !B && C) || (A && B && !C) || (A && B && C)"

The variables A, B and C will have your boolean values (true or false).

How I can transforming a string expression, replace the logic values and validate using C#?

like image 846
Jose Felipe Blum de Araujo Avatar asked Aug 24 '16 02:08

Jose Felipe Blum de Araujo


1 Answers

If you don't want to use some available libraries to parse that string you need to separate those characters and implement the logic based on comparison. So for example say we have "a || b", we can loop though each character and decide the appropriate operation based on char == '|'. For more complex situation I'd use a stack to keep track of each results, like this one that can handle && and || without parentheses:

public bool ConvertToBool(string op, bool a, bool b)
{
    var st = new Stack<bool>();
    var opArray = op.ToCharArray();
    var orFlag = false;
    var andFlag = false;

    for (var i = 0; i < opArray.Length; i++)
    {
        bool top;
        switch (opArray[i])
        {
            case '|':
                i++;
                orFlag = true;
                break;
            case '&':
                i++;
                andFlag = true;
                break;
            case 'a':
                if (orFlag)
                {
                    top = st.Pop();
                    st.Push(top || a);
                    orFlag = false;
                }
                else if (andFlag)
                {
                    top = st.Pop();
                    st.Push(top && a);
                    andFlag = false;
                    continue;
                }
                st.Push(a);
                break;
            case 'b':
                if (orFlag)
                {
                    top = st.Pop();
                    st.Push(top && b);
                    orFlag = false;
                }
                else if (andFlag)
                {
                    top = st.Pop();
                    st.Push(top && b);
                    andFlag = false;
                    continue;
                }
                st.Push(b);
                break;
        }
    }
    return st.Pop();
}
like image 73
Yar Avatar answered Nov 10 '22 00:11

Yar