2013-03-16 58 views
11

我现在有点困惑。我试过:为什么String.replace不起作用?

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

,并得到:

KP 175.105 

不过,我想:

175.105 

这有什么错我的代码?

+0

顺便说一句对不起我的愚蠢的问题。我想它的时间去睡觉... – maximus 2013-03-16 14:40:02

+0

这个问题可能是重复的,但它比它被认为是重复的更容易理解。 – Suragch 2015-05-04 03:42:24

回答

35

你没有分配到test.Strings是immutable

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

需要分配到再次测试。

9

Strings是不可变的,所以你需要你的test引用赋予的String.replace结果:

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

字符串是在Java中不变的,所以你要做的

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