I am trying to replace " with \" in Java, but all the slashes are getting very confusing. What is the proper way to replace " with \" in Java?
string.replaceAll("\"","\\"");
I am trying to replace " with \" in Java, but all the slashes are getting very confusing. What is the proper way to replace " with \" in Java?
string.replaceAll("\"","\\"");
If you are going to replace literals then don't use replaceAll but replace.
Reason for this is that replaceAll uses regex syntax which means that some characters will be treated specially like + * \ ( ) and to make them literals you will need to escape them. replace adds escaping mechanism for you automatically, so instead of
replaceAll("\"", "\\\\\"")
you can write
replace("\"", "\\\"");
which is little less confusing.
Try to use char:
public void bsp(){
//34 = " ; 92 = \
String replace = "\"";
String replace2 = "\\";
text.replace(replace.charAt(0),replace2.charAt(0));
}
string.replaceAll("\"", "\\\"");
Let's explain:
"\"" : is a string with \" an escaped " char
"\\\"": is a string with a \\ an escaped \ char and a \" an escapd " char