I have this string in my Java code which is coming from a URL:
String str = "C:\Program Files\Text.txt";
And I want to replace it to make it somewhat like this
String str = "C:\\\Program Files\\\Text.txt";
But Java isn't accepting str and also I cannot manually make the single backslash as double backslash everytime because it's coming from an URL. The code is showing this error below:
error: illegal escape character
String str = "C:\Program Files\Text.txt";
I have already tried "replace" and "replaceAll" but the issue is, it is not accepting my input so obviously it is not compiling. All in all my question is how do I take this string as input, String str = "C:\Program Files\Text.txt";
public class Example {
public static void main(String[] args) {
String str = "C:\Program Files\Text.txt";
str = str.replace("\", "\\");
System.out.println(str);
}
}
Backslash is an escape sequence character, You can read about it here . It needs to be prefixed with \
.You need to do this:
String str = "C:\\Program Files\\Text.txt";
str = str.replace("\\", "\\\\");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.