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

1

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.