Consider the following code:
class Sample{
public static void main(String args[]){
String text1="C:\Documents\User\sample";
String text2=text1.replace('\','/');
System.out.println(text2);
}
}
I have an input where the text1 is receiving a file path. Now I want to replace all the “\” in text1 to “/”. I have used the code above.
First of all, the error shown is : “Illegal Escape Sequence” which is understandable and is not my issue because I am making a Java EE application where the user enters the path in the input box.
But I have trouble changing the “\” into “/” which is essential for my code to run properly. I am not able to solve this problem. I have even tried using String.replaceAll() method, but no result.
You need to escape the backslash:
By the way,
replaceAll()would make your problem even more complicated: Now you’re dealing with a regex instead of a simple string replace, and that means your backslashes need to be escaped yet again for the regex engine: