I want to change the backslash in a string to double backslash.
I have
String path = "C:\Program Files\Text.txt";
and I want to change it to
"C:\\Program Files\\Text.txt"
I want to change the backslash in a string to double backslash.
I have
String path = "C:\Program Files\Text.txt";
and I want to change it to
"C:\\Program Files\\Text.txt"
replaceAll
is using regex, and since you don't need to use regex here simply use
path = path.replace("\\", "\\\\");
\
is special in String literals. For instance it can be used to
\t
, line separators \n
\r
, \uXXXX
(where X
is hexadecimal value and XXXX
represents position of character in Unicode Table). To escape it (and create \
character) we need to add another \
before it.
So String literal representing \
character looks like "\\"
. String representing two \
characters looks like "\\\\"
.
Using String#replace()
String s= "C:\\Program Files\\Text.text";
System.out.println(s.replace("\\", "\\\\"));