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"
Double Backslashes (\\) Two backslashes are used as a prefix to a server name (hostname). For example, \\a5\c\expenses is the path to the EXPENSES folder on the C: drive on server A5.
To replace all backslashes in a string: Call the replaceAll() method, passing it a string containing two backslashes as the first parameter and the replacement string as the second. The replaceAll method will return a new string with all backslashes replaced by the provided replacement.
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 "\\\\" .
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("\\", "\\\\"));
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