我觉得我在这里漏掉了什么——string.replace()

4
我有这段代码。
String txt = "<p style=\"margin-top: 0\">";
txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

在 for 循环中(这就是 i 的作用),但当我运行此代码时,没有任何替换。我使用方法不正确吗?
3个回答

8
它应该看起来像这样:
String txt = "<p style=\"margin-top: 0\">";
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

"String"是一种不可变类型,这意味着对String的操作并不会改变String本身。更多信息请参考 - http://en.wikipedia.org/wiki/Immutable_object

1
哦,哇。我简直不敢相信我错过了这个。我想我需要休息一下。谢谢。 - Samsquanch

2
replace方法不会修改被调用的字符串,而是返回对修改后字符串的引用。
如果您想让txt引用修改后的字符串,可以这样做:
txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

如果你想让txt继续引用原始字符串,并希望有另一个引用来引用更改后的字符串,则可以执行以下操作:

String new_txt = txt.replace("style=\"margin-top: 0\"","class=\"style_" + i + "\"");

1

String是一个不可变类,这意味着String对象的实例方法不会改变字符串本身。您必须收集这些实例方法的返回值。


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