Infix expression to postfix expression--C# code implementation

Converting Expressions Using Computers The standard four arithmetic expressions we
usually use, such as "1+(2-3)*4/5", are called infix expressions, ,,
and the rules for infix-to-suffix expressions are:

  • Each number and symbol of the variable infix expression from left to right, if it is a number, it is output, that is, it becomes part of the following expression. If it is a symbol, it is judged that it has a priority with the symbol on the top of the stack, which is the right parenthesis or the limited level low On the top of the stack symbol (multiply and divide first, then add and subtract), the top elements of the stack are popped out of the stack and output in turn, and the current symbol is pushed onto the stack until the suffix expression is finally output,,,

Take "9+(3-1) × 3+10÷2" as an example to
initialize an air battle to push symbols into the stack,
1
the first character is 9, output 9, followed by the symbol "+", push into the stack, ,
the third character is "(", it is still a symbol, because it is only the symbol "+", and it is also a pair, so it is pushed into the stack, and
the fourth character is the number 3, output, the total expression is 9 3 followed by " -", into the stack,,,
2
followed by the number 1, output, the total expression is 9, 3, followed by the symbol ")", at this time we need to match the previous "(", so the top of the stack is in turn Pop the stack and output until "(" pops the stack, at this time there is only "-" above the left parenthesis, so output "-", the total output expression is 9 3 1 - ,,,
followed by the number 3,, Output, the total expression is 9 3 1 - 3 , followed by the symbol " × ", because the symbol at the top of the stack at this time is " + ", the priority is lower than " * ", so no output, " * "Push into the stack,
3
followed by the symbol "+", at this time, the current top element of the stack is " × " has a higher priority than " + ", so the elements in the stack are popped and output (nothing lower than the root of the "+" sign Priority, so all pop out of the stack),, the total output expression is 9 3 1 - 3 × +, and then push the current symbol "+" into the stack,
followed by the number 10, and the total output expression is: 9 3 1 - 3 * + 10 is followed by "÷", so "/" pushes
the last , output, and then all the symbols in the stack are output, that is, the final expression is: 9 3 1 - 3 * + 10 2 / +
write picture description here


Implementation method: mainly use the characteristics of the stack, and then use the idea of ​​​​a state machine to realize,,, treat "+-", "*/", "(", ")" as a state, and then implement one by one. Jump between each state,,,It is worth noting that the next step of each state may be four states, Be sure to discuss all the inputs , and then consider the next state,,, Click to view the state Simple example of machine

The following is the code implemented using the above ideas,,,, once the
previous question is modified, please leave a message if there is any error.

namespace 玩嗨的练习
    {
        class Program
        {
            static void Main(string[] args)
            {
                //运行时用建议输入空格
                Console.WriteLine("请输入您要转换的表达式:");
                string inputstr = Console.ReadLine();
                //测试用
                //string inputstr = "9 * (3 - 1) + (10 - 1) / 2";
                //string inputstr = "1 - 2 - 3 * 4 + 10 / 5";
                Console.WriteLine("您转换后的结果为:");
                Change(inputstr);

                Console.ReadKey();
            }

            private static void Change(string inputstr)
            {
                Stack<char> arrStark = new Stack<char>();

                char[] arrChar = inputstr.ToCharArray();


                int a = 4;  //默认状态是什么都没有,这里是4状态,,

                for (int i = 0; i < arrChar.Length; i++)
                {
                    //数字空格就直接输出
                    if (arrChar[i] <= '9' && arrChar[i] >= '0')
                    {
                        Console.Write(arrChar[i]);
                    }
                    if (arrChar[i] == ' ')
                    {
                        Console.Write(" ");
                    }

                    //运算符走状态机
                    switch (a)
                    {
                        //=============================状态1 * / ====================================
                        case 1:  //表示当前是+- 状态
                            if (arrChar[i] == '+' || arrChar[i] == '-')
                            {
                                a = 1;
                                Console.Write(arrStark.Pop());
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == '*' || arrChar[i] == '/')
                            {
                                a = 2;
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == '(')
                            {
                                a = 3;
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == ')')
                            {
                                a = 4;
                                for (int j = 0; j < arrStark.Count; j++)
                                {
                                    //输出括号中间的符号,,,
                                    if (arrStark.Peek() == '(')
                                    {
                                        //把左括号,,弹出栈外
                                        arrStark.Pop();
                                        break;
                                    }
                                    else
                                    {
                                        Console.Write(arrStark.Pop());
                                    }
                                }
                            }
                            break;
                        //=============================状态2 * / ====================================
                        case 2:  //表示当前是* / 状态
                            if (arrChar[i] == '+' || arrChar[i] == '-')
                            {
                                a = 1;
                                for (int j = 0; j <= arrStark.Count; j++)
                                {
                                   //Console.Write(arrStark.Count);
                                   Console.Write(arrStark.Pop());
                                }
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == '*' || arrChar[i] == '/')
                            {
                                a = 2;
                                Console.Write(arrStark.Pop());
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == '(')
                            {
                                a = 3;
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == ')')
                            {
                                a = 4;
                                for (int j = 0; j < arrStark.Count; j++)
                                {
                                    if (arrStark.Peek() == '(')
                                    {
                                        //把左括号,,弹出栈外
                                        arrStark.Pop();
                                        break;
                                    }
                                    else
                                    {
                                        //输出括号中间的符号,,,
                                        Console.Write(arrStark.Pop());
                                    }
                                }
                            }
                            break;
                        //=============================状态3 ) ====================================
                        case 3:  //表示当前是( 状态
                            if (arrChar[i] == '+' || arrChar[i] == '-')
                            {
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == '*' || arrChar[i] == '/')
                            {
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == '(')
                            {
                                a = 3;
                                arrStark.Push(arrChar[i]);
                            }
                            else
                            if (arrChar[i] == ')')
                            {
                                a = 4;
                                for (int j = 0; j < arrStark.Count; j++)
                                {
                                    if (arrStark.Peek() == '(')
                                    {
                                        //把左括号,,弹出栈外
                                        arrStark.Pop();
                                        break;
                                    }
                                    else
                                    {
                                        //输出括号中间的符号,,,
                                        Console.Write(arrStark.Pop());
                                    }
                                }
                            }
                            break;
                        //=============================状态4 ( ====================================
                        case 4:  //表示当前是 )  状态
                            if (arrChar[i] == '+' || arrChar[i] == '-')
                            {
                                if (arrStark.Count == 0)
                                {
                                    a = 1;
                                    arrStark.Push(arrChar[i]);
                                }
                                else
                                {
                                    if (arrStark.Peek() == '+' || arrStark.Peek() == '-')
                                    {
                                        a = 1;
                                        arrStark.Push(arrChar[i]);
                                    }
                                    else
                                    if (arrStark.Peek() == '*' || arrStark.Peek() == '/')
                                    {
                                        a = 1;
                                        for (int j = 0; j < arrStark.Count; j++)
                                        {
                                            Console.Write(arrStark.Pop());
                                        }
                                        arrStark.Push(arrChar[i]);

                                    }
                                }
                            }
                            else
                            if (arrChar[i] == '*' || arrChar[i] == '/')
                            {
                                if (arrStark.Count == 0)
                                {
                                    a = 2;
                                    arrStark.Push(arrChar[i]);
                                }
                                else
                                {
                                    if (arrStark.Peek() == '+' || arrStark.Peek() == '-')
                                    {
                                        a = 2;
                                        arrStark.Push(arrChar[i]);

                                    }
                                    else if (arrStark.Peek() == '*' || arrStark.Peek() == '/')
                                    {
                                        a = 2;
                                        arrStark.Push(arrChar[i]);

                                    }
                                }
                            }
                            else
                            if (arrChar[i] == '(')
                            {
                                a = 3;
                                arrStark.Push(arrChar[i]);
                            }
                            if (arrChar[i] == ')')
                            {
                                a = 4;
                                for (int j = 0; j < arrStark.Count; j++)
                                {
                                    if (arrStark.Peek() == '(')
                                    {
                                        //把左括号,,弹出栈外
                                        arrStark.Pop();
                                        break;
                                    }
                                    else
                                    {
                                        //输出括号中间的符号,,,
                                        Console.Write(arrStark.Pop());
                                    }
                                }
                            }
                            break;
                        default:
                            Console.WriteLine("Wrong");
                            break;

                    }
                }
                //遍历栈中剩余的符号输出,并清空栈,
                foreach (char item in arrStark)
                {
                    Console.Write(" " + item);
                }
                arrStark.Clear();

            }

      }
}

Test renderings:
Test 1
Test 2

Guess you like

Origin blog.csdn.net/Czhenya/article/details/78067542