Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace backslash with double backslash [duplicate]

Tags:

java

string

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"
like image 310
user2060390 Avatar asked Feb 23 '13 13:02

user2060390


People also ask

How do you do a double backslash?

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.

How do you replace a backslash?

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.

How do you write a double backslash in Java?

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 "\\\\" .


2 Answers

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

  • create special characters like tab \t, line separators \n \r,
  • or to write characters using notation like \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 "\\\\".

like image 157
Pshemo Avatar answered Oct 01 '22 17:10

Pshemo


Using String#replace()

String s= "C:\\Program Files\\Text.text";
System.out.println(s.replace("\\", "\\\\"));
like image 21
PermGenError Avatar answered Oct 01 '22 17:10

PermGenError