【问题标题】:I think I'm missing something here -- string.replace()我想我在这里遗漏了一些东西——string.replace()
【发布时间】:2011-05-14 21:30:45
【问题描述】:

我有密码

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

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

【问题讨论】:

    标签: java string replace


    【解决方案1】:

    应该是这样的:

    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

    【讨论】:

    • 哇哦。我不敢相信我错过了这个。我想我需要休息一下。谢谢。
    【解决方案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 + "\"");
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 2019-03-12
        • 1970-01-01
        • 2013-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多