简体   繁体   中英

ReplaceAll and " doesn't replace

Can anyone point me out how the first if works and the second doesn't? I'm puzzled why the second if-clause isn't working. I'd like to get a hint, thanks.

String msg = o.getTweet();
        if (msg.indexOf("&") > 0) {
            msg = msg.replaceAll("&", "&");// vervangt & door &
        }
        if (msg.indexOf(""") > 0) {
            msg = msg.replaceAll(""", "aa"); //vervangt " door "
        }

Because ZERO is a very valid index. Try this out,

    String msg = o.getTweet();
    if (msg.indexOf("&") != -1) {
        msg = msg.replaceAll("&", "&");// vervangt & door &
    }
    if (msg.indexOf(""") != -1) {
        msg = msg.replaceAll(""", "aa"); //vervangt " door "
    }

Explanation:

The documentation of String.indexOf(String str) explains that, "if the string argument occurs as a substring within this object, then the index of the first character of the first such substring is returned; if it does not occur as a substring, -1 is returned." - [link to docs]

This can be done as simple as below, as OpenSauce pointed out here .

msg = msg.replace("&", "&").replace(""", "\"");

Useful links:

You don't need to check the substring exists, the replace and replaceAll methods are no-ops if the substring is not found. Since you're not looking for regexes, you can also use replace instead of replaceAll - it will be somewhat more efficient, and won't surprise you if you also want to check for other strings which happen to contain regex special chars.

msg = msg.replace("&", "&").replace(""", "\"");

note that replace does indeed replace all matches, like you want. The difference between replace and replaceAll is whether the arg is interpreted as a regex or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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