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