Skip to content Skip to sidebar Skip to footer

Replace "\\" With "/" In Java

I am trying to replace '\\'with '/' in java(Android) and this does not seem to work! String rawPath = filePath.replace('\\\\', '/'); What is wrong with this ? I have escaped '\' a

Solution 1:

When using String.replace(String, String) the backslash doesn't need to be escaped twice (thats when using replaceAll - it deals with regex). So:

StringrawPath= filePath.replace("\\", "/");

Or using char version:

StringrawPath= filePath.replace('\\', '/');

Solution 2:

You do not need the quad-druple escape,

\\\\

, just simply

\\

.

Solution 3:

escape with single slash should be enough. Following is working fine for me.

String rawPath = filePath.replace("\\", "/");

Solution 4:

publicstaticvoidmain(String[] args) {
    String s = "foo\\\\bar";
    System.out.println(s);
    System.out.println(s.replace("\\\\", "/"));     
}

will print

foo\\bar
foo/bar

Solution 5:

If you want to replace a sequence of 2 backslashes in your original string with a single forward slash, this should work:

String filePath ="abc\\\\xyz";
String rawPath = filePath.replace("\\\\", "/");

System.out.println(filePath);
System.out.println(rawPath);

outputs:

abc\\xyz  
abc/xyz

Post a Comment for "Replace "\\" With "/" In Java"