Java中如何用单词替换字符

Java中如何用单词替换字符,java,replace,postfix-notation,infix-notation,Java,Replace,Postfix Notation,Infix Notation,我有一个像这样的输入字符串,它接受中缀表达式:stringstr=“-(4-2)” 我的输出字符串以后缀表达式的形式返回字符串值:42--- 如何将42---末尾的-符号替换为negate,使我的输出看起来像42-negate 我尝试使用str.replace,但它不起作用,因为只能用char替换char或用string替换string 我的从中缀表达式转换为后缀表达式的代码: private int precedence(Character character) { switch (c

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

我的输出字符串以后缀表达式的形式返回字符串值:
42---

如何将
42---
末尾的
-
符号替换为
negate
,使我的输出看起来像
42-negate

我尝试使用
str.replace
,但它不起作用,因为只能用char替换char或用string替换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;
}
private int优先级(字符)
{
开关(字符)
{
格“+”:
案例'-':
返回1;
案例“*”:
案例“/”:
案例“%”:
返回2;
}
返回0;
}
@重写公共T visitExp(ExpAnalyserParser.ExpContext ctx){
字符串后缀=”;
堆栈=新堆栈();
for(int i=0;i而(!stack.isEmpty()&&priority(c)一种方法是使用
子字符串删除最后一个字符,然后将单词连接到末尾:

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

ReplaceAll听起来有悖常理,它使用正则表达式,因此您可以在字符串末尾指定减号:

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

str.replace(“-”,“negate”)
或者如果您想更改
字符串的特定部分,您必须执行多个
String
方法,例如
str.substring(str.lastIndexOf(“-”)
@you刺客我假设问题是OP使用的
'-'
“-”
对吗?你能给出一个例子来展示你的尝试吗?当然,你的后缀转换器知道什么时候找到了一个否定而不是减法,所以它可以直接输出
否定
,而不是你必须破解输出;你如何确定最后一个
-
是否定,而不仅仅是减法,比如
4 3 2--
?否则问题只是“如何用字符串替换字符串的最后一个字符”,这就是您的标题;我们在这里找到了吗?@KenY-N您有一个很好的观点。我将在后缀转换器代码中进行编辑,以便您可以看到我是如何做到的。