Replace All method in Strings



我想用replace all方法替换字符串中的一个字符,但这个方法仍然给我相同的字符串。

String example = "5x";
example.replaceAll(Character.toString('x') , Integer.toString(1));

代码出了什么问题?

String是不可变的。你应该做一些类似的事情

example = example.replaceAll(Character.toString('x') , Integer.toString(1));

字符串是不可变的,这意味着它们不能更改。

这可以简单地这样做:

String example = "5x";
example = example.replaceAll("x", Integer.toString(1));

您缺少将新字符串分配给示例。

最新更新