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 = "http://test.com/awesomeness.asp?page=27";
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.
Escape the \
too, using \\\\?
.
String longstring = "..."; //This is the long String
String replacestring = "http://test.com/awesomeness.asp?page=27";
longstring=longstring.replaceAll(replacestring, "\\\\?");
But as other answer have mentioned, replaceAll
is a bit overkill, just a replace
should work.
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