Converting string expression to boolean logic - C#
Asked Answered
K

1

6

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#?

Klute answered 24/8, 2016 at 2:57 Comment(1)
Possible duplicate of Evaluating string "3*(4+2)" yield int 18Zuckerman
V
1

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();
}
Vertu answered 24/8, 2016 at 4:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.