Replace backslash with double backslash

I want to change the backslash in a string to double the backslash.

I have

String path = "C:\Program Files\Text.txt"; 

and I want to change it to

 "C:\\Program Files\\Text.txt" 
+6
source share
2 answers

replaceAll uses a regex, and since you don't need to use a regex, just use

 path = path.replace("\\", "\\\\"); 

\ is special in string literals. For example, it can be used to

  • create special characters like tab \t , line separators \n \r ,
  • or to write characters using type notation \uXXXX (where X is a hexadecimal value and XXXX represents the character position in the Unicode table).

To avoid it (and create the \ character), we need to add another \ in front of it.
Thus, the string literal representing the \ character looks like "\\" . A string representing the two characters \ looks like "\\\\" .

+14
source

Using String # replace ()

 String s= "C:\\Program Files\\Text.text"; System.out.println(s.replace("\\", "\\\\")); 
+8
source

All Articles