OneBite.Dev - Coding blog in a bite size

escape a string in java

Code snippet on how to escape a string in java

String inputString = "Hello! World?";
String escapedString = inputString.replace("!", "\\!").replace("?", "\\?");

This code replaces two characters in the input string, the exclamation point (!) and the question mark (?). To do this, the replace method is used. The replace method takes two parameters - the character we want to replace and the character we want to replace it with - and it will return a new string with the desired changes. For the exclamation point, the character we want to replace is again the exclamation point, but this time we need to “escape” this character so it won’t be treated as a string delimiter. The same applies to the question mark. To escape both characters, we add an additional backslash (\) in the second parameter of the replace method. As a result, the code returns a new string that replaces “!” with “!” and “?” with “?”.

java