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 "
}
\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.
Java String replaceAll() The Java String class replaceAll() method returns a string replacing all the sequence of characters matching regex and replacement string.
The replaceAll() method returns a new string with all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function to be called for each match. The original string is left unchanged.
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:
indexOf()
docsreplace()
docsreplaceAll()
docsYou 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With