gpt4 book ai didi

Java 的 String.replaceAll 不起作用

转载 作者:行者123 更新时间:2023-12-01 07:06:18 24 4
gpt4 key购买 nike

我正在构建一个表示多项式的字符串。我试图用“”替换所有 ^1 和 x^0 以简化使用 ReplaceAll 方法的输出。但是,当我运行代码时,它没有检测到任何目标字符串。

public String toString() {
String output = "";
boolean isFirst = true;
for(Node current = head; current != null; current = current.next) {
if(isFirst) {
output += current.coefficient + "x^" + current.exponent;
isFirst = false;
}
else if(current.coefficient < 0)
output += " - " + current.coefficient*-1 + "x^" + current.exponent;
else
output += " + " + current.coefficient + "x^" + current.exponent;
}
output.replaceAll("x^0", "");
output.replaceAll("^1", "");
return output;
}

最佳答案

字符串是不可变的。您无法更改字符串。因此,replacereplaceAll 方法返回一个新的字符串。这里试试这个:

output = output.replaceAll("x^0", "");
output = output.replaceAll("^1", "");

关于Java 的 String.replaceAll 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23231651/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com