Here's an excerpt from the documentation:
public String replace(CharSequence target, CharSequence replacement)
:
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence. The replacement proceeds from the beginning of the string to the end, for example, replacing "aa"
with "b"
in the string "aaa"
will result in "ba"
rather than "ab"
.
So the error in this particular case is that you've swapped the arguments around.
System.out.println( "a\\b" ); // "a\b"
System.out.println( "a\\b".replace("", "\\") ); // "\a\\\b\"
System.out.println( "a\\b".replace("\\", "") ); // "ab"
Note that you don't really need to do an if/contains
check: if target
is not found in your string, then no replacement
will be made.
System.out.println("a+b".replace("\\", "")); // "a+b"