Why does String.replace not work? [duplicate]

2020-01-25 09:17发布

I am a little bit confused at the moment. I tried that:

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

and got:

KP 175.105

However, I want:

175.105

What's wrong with my code?

3条回答
▲ chillily
2楼-- · 2020-01-25 10:15

String is immutable in java so you have to do

test =test.replace("KP", "");
查看更多
狗以群分
3楼-- · 2020-01-25 10:16

Strings are immutable so you need to assign your test reference to the result of String.replace:

test = test.replace("KP", "");
查看更多
Fickle 薄情
4楼-- · 2020-01-25 10:19

you did not assigned to test.Strings are immutable

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

you need to assign to test again.

查看更多
登录 后发表回答