简体   繁体   English

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

[英]How to replace a character with a word in Java

I have an input string like so which takes in infix expressions: String str = "-(4-2)";我有一个像这样的输入字符串,它采用中缀表达式: String str = "-(4-2)";

My output string returns a string value in the form of postfix expressions: 4 2 - -我的输出字符串以后缀表达式的形式返回一个字符串值: 4 2 - -

How can I replace the - sign at the end of 4 2 - - with negate so that my output looks like 4 2 - negate ?如何用negate替换4 2 - -末尾的-符号,以便我的输出看起来像4 2 - negate

I tried using str.replace but it won't work because you can only replace char with char or string with string.我尝试使用str.replace但它不起作用,因为您只能用 char 替换 char 或用字符串替换字符串。

My code for converting from infix to postfix expression:我的从中缀转换为后缀表达式的代码:

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;
}

Any help will be appreciated.任何帮助将不胜感激。

ReplaceAll, which sounds counterintuitive, uses regular expressions, and so you can specify the minus at the end of the String: ReplaceAll 听起来违反直觉,它使用正则表达式,因此您可以在 String 的末尾指定减号:

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM