我想我在这里遗漏了一些东西 - string.replace()

Sam*_*nch 4 java string replace

我有代码

String txt = "<p style=\"margin-top: 0\">";
txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
Run Code Online (Sandbox Code Playgroud)

在for循环中(这就是我的目的),但是当我运行它时,没有任何东西被替换.我用错了吗?

Gre*_*som 8

它应该如下所示:

String txt = "<p style=\"margin-top: 0\">";
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");
Run Code Online (Sandbox Code Playgroud)

"String"是一个不可变类型,这意味着String上的方法不会更改String本身.更多信息,请访问http://en.wikipedia.org/wiki/Immutable_object.