【发布时间】:2018-02-21 23:38:38
【问题描述】:
我有一个像这样的输入字符串,其中包含中缀表达式:String str = "-(4-2)";
我的输出字符串以后缀表达式的形式返回一个字符串值:4 2 - -
如何将4 2 - - 末尾的- 符号替换为negate,以便我的输出看起来像4 2 - 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;
}
任何帮助将不胜感激。
【问题讨论】:
-
str.replace("-", "negate")或者如果您想要更改String的特定部分,您将不得不执行多个String方法,例如str.substring(str.lastIndexOf('-')) -
@youassassin 我认为问题是 OP 使用了
'-'而不是"-"对吧? -
你可以给minimal reproducible example 来展示你的尝试吗?
-
当然你的后缀转换器知道它什么时候找到了一个否定而不是一个减法,所以它可以直接输出
negate,而不是你不得不破解输出;你如何确定最后一个-是否定的,而不仅仅是减法,比如4 3 2 - -?否则问题只是“如何用字符串替换字符串的最后一个字符”,这就是您的标题;我们这里有XY Problem 吗? -
@KenY-N 你说得很好。我将编辑我的后缀转换器代码,以便您了解我是如何做到的。
标签: java replace postfix-notation infix-notation