如何用Java中的单词替换字符

时间:2018-02-21 23:38:38

标签: java replace postfix-notation infix-notation

我有一个像这样的输入字符串,它接受中缀表达式:String str = "-(4-2)";

我的输出字符串以后缀表达式的形式返回一个字符串值:4 2 - -

如何使用-替换4 2 - -末尾的negate符号,以便我的输出看起来像4 2 - negate

我尝试使用str.replace但它不起作用,因为你只能用char替换char或用string替换字符串。

我从中缀转换为后缀表达式的代码:

private int precedence(Character character)
{
    switch (character)
    {
        case '+':
        case '-':
            return 1;

        case '*':
        case '/':
        case '%':
            return 2;
    }
    return 0;
}

@Override public T visitExp(ExpAnalyserParser.ExpContext ctx) {
    String postfix = "";
    Stack<Character> stack = new Stack<>();

    for (int i = 0; i< ctx.getText().length(); i++) {
        char c = ctx.getText().charAt(i);

        if (Character.isDigit(c)) {
            postfix += c;
        }

        else if (c == '(') {
            stack.push(c);
        }

        else if (c == ')') {
            while (!stack.isEmpty() && stack.peek() != '(') {
                postfix += " " + (stack.pop());
            }

            if (!stack.isEmpty() && stack.peek() != '(')
                System.out.println("Invalid Expression");
            else
                stack.pop();
        }
        else {
            postfix += " ";
            while (!stack.isEmpty() && precedence(c) <= precedence(stack.peek()))
                postfix += (stack.pop()) + " " ;
            stack.push(c);
        }
    }

    while (!stack.isEmpty()){
        postfix += " " + (stack.pop());
    }

    postfix = postfix.replace("%", "mod");

    try(FileWriter out = new FileWriter("postfix.txt")){
        out.write(postfix);
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println("Infix Expression: " + ctx.getText());
    return (T) postfix;
}

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

ReplaceAll,听起来违反直觉,使用正则表达式,因此您可以在字符串末尾指定减号:

-> str.replaceAll ("-$", "negate");
|  Expression value is: "4 2 - negate"
|    assigned to temporary variable $14 of type String

答案 1 :(得分:0)

一种方法是使用substring删除最后一个字符,然后将单词连接到结尾:

str = str.substring(0, str.length() - 1) + "negate";