为什么String.replace无法正常工作?

50

我现在有点困惑。我尝试了这个:

String test = "KP 175.105";
test.replace("KP", "");
System.out.println(test);

并获得:

KP 175.105

不过,我希望:

175.105

我的代码有什么问题?

3个回答

164
你没有将它分配给 test 。字符串是不可变的。
test = test.replace("KP", "");
你需要把它重新分配给test

5
你不知道你救了我多少痛苦。非常感谢你。 - Brenann
无法工作的是"...",""。 - withoutOne

22

字符串是不可变的,因此您需要将您的test引用赋值给String.replace的结果:

test = test.replace("KP", "");

7

Java中的字符串是不可变的,因此您需要执行

test =test.replace("KP", "");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接