简体   繁体   中英

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)";

My output string returns a string value in the form of postfix expressions: 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 ?

I tried using str.replace but it won't work because you can only replace char with char or string with string.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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