简体   繁体   English

String#replace在我的方法中不起作用

[英]String#replace won't work in my method

As I get an HTML file containing some wild chars like ⋍ 当我得到一个HTML文件时,其中包含一些⋍ or 𖫻 𖫻 , I want to replace them with a bullet. ,我想用子弹代替它们。 So I wrote this method : 所以我写了这个方法:

public String replaceAmps(String initial)
{
    // This list will contain all the &amps; to replace.
    ArrayList<String> amps = new ArrayList<String>();
    String res = initial;
    int index = initial.indexOf("&amp;");
    // Get all the indexes of &amp.
    while (index >= 0) 
    {
        StringBuilder stb = new StringBuilder("&amp;");
        // Create a String until the next ";", for example &amp;#1091;<- this one
        for(int i = index+5 ; initial.charAt(i) != ';' ; i++) stb.append(initial.charAt(i));
        stb.append(";");
        // Add the amp if needed in the list.
        if(!amps.contains(stb.toString())) amps.add(stb.toString());
        index = initial.indexOf("&amp;", index + 1);
    }
    // Replace the Strings from the list with a bullet.
    for(String s : amps) res.replace(s, "•");
    return res;
}

I correctly get all the amps in my list, but the replacing doesn't work. 我可以在列表中正确找到所有放大器,但是替换不起作用。 Why? 为什么? Thanks for your help. 谢谢你的帮助。

Strings are immutable; 字符串是不可变的。 the replace method returns a new String as the result of the replacement and does not modify res . replace方法将作为替换的结果返回一个新的String ,并且不会修改res Try 尝试

for(String s : amps) res = res.replace(s, "•");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM