InfixToPostfix将char转换为字符串

时间:2015-10-18 17:49:56

标签: shunting-yard

如何将此代码中的字符转换为字符串? InfixToPostfix必须能够接受字符串而不是字符,因此它可以接受两位数字和空格。有什么建议?提前谢谢。

import java.util.Stack;

public class InfixToPostfix
{
private Stack operators = new Stack();

public InfixToPostfix()
{

}

public String toPostfix(String infix)
{
    char[] characters = new char[100];
    int i;
    int length = infix.length();
    infix.getChars(0, length, characters, 0);
    char operator;
    String output = "";

    for (i = 0; i < length; i++)
    {
        if (isOperator(characters[i]))
            if (operators.empty())

                operators.push(characters[i]);
            else
            {
                if (operatorLessPrecedence(characters[i]))

                {
                    do
                    {
                        output = output + operators.pop();
                    }
                    while (!operators.empty() && operatorLessPrecedence(characters[i]));
                    operators.push(characters[i]);
                }
                else

                    operators.push(characters[i]);
            }
        else

            output = output + characters[i];
    }
    while (!operators.empty())
    {

        operator = (char)operators.pop();
        output = output + operator;
    }
    return output;
}

/**
 * operator
 */

public boolean isOperator(char c)
{
    if ( c == '*' ||
         c == '/' ||
         c == '+' ||
         c == '^' ||
         c == '-')
        return true;
    else
        return false;
}


public boolean operatorLessPrecedence(char o)
{
    int operatorPrecedence = precedence(o);
    int tosPrecedence = precedence((char)operators.peek());
    return (operatorPrecedence <= tosPrecedence);
}

/**
 * precedence
 */
public int precedence(char o)
{
    switch (o)
    {
        case '+': return 1;
        case '-': return 1;
        case '*': return 2;
        case '/': return 2;
        case '^': return 3;
    }
    return 5;
}

}

1 个答案:

答案 0 :(得分:0)

我会将代码分成两部分,并使用词法分析阶段将输入分成一组标记。然后将它们传递给分流码算法,该算法使用一系列令牌。在lexing阶段,您可以使用正则表达式来检测不同类型的输入。说/ \ d + /检测一个或多个数字的序列。