GuiceU GuiceU - 2 months ago 14
Java Question

Replace all "?" with "\\?" in Java

is it possible to replace all the questionmarks ("?") with "\?" ?

Lets say I have a String, and I want to delete some parts of that String, one part with an URL in it. Like this:

String longstring = "..."; //This is the long String
String replacestring = "";
longstring.replaceAll(replacestring, "");

But! As I understand it you can't use the replaceAll() method with a String that contains one single questionmark, you have to make them like this "\?" first.

So the question is; Is there some way to replace questionmarks with "\?" in a String? And no, I'm able to just change the String.

Thanks in advance, hope someone understands me! (Sorry for bad English...)


Don't use replaceAll(), use replace()!

It is a common misconception that replaceAll() replaces all occurrences and replace() just replaces one or something. This is totally incorrect.

replaceAll() is poorly named - it actually replaces a regex.
replace() replaces simple Strings, which is what you want.

Both methods replace all occurrences of the target.

Just do this:

longstring = longstring.replace(replacestring, "");

And it will all work.