5

In java, I have a file path, like 'C:\A\B\C', I want it changed to ''C:/A/B/C'. how to replace the backslashes?

Ken Liu
  • 22,503
  • 19
  • 75
  • 98
user534009
  • 1,419
  • 4
  • 23
  • 25

5 Answers5

15
    String text = "C:\\A\\B\\C";
    String newString = text.replace("\\", "/");
    System.out.println(newString);
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
11

Since you asked for a regular expression, you'll have to escape the '\' character several times:

String path = "c:\\A\\B\\C";
System.out.println(path.replaceAll("\\\\", "/"));
Isaac Truett
  • 8,734
  • 1
  • 29
  • 48
  • +1 for noticing (and being responsive to) the "regex" tag, even though the problem doesn't actually need regular expressions. – Ted Hopp Apr 22 '11 at 15:27
1

You can do this using the String.replace method:

public static void main(String[] args) {
    String foo = "C:\\foo\\bar";
    String newfoo = foo.replace("\\", "/");
    System.out.println(newfoo);
}
bedwyr
  • 5,774
  • 4
  • 31
  • 49
0

To replace all occurrences of a given character :

String result = candidate.replace( '\\', '/' );

Regards, Cyril

Cyril Deba
  • 1,200
  • 2
  • 16
  • 30
0
String oldPath = "C:\\A\\B\\C";
String newPath = oldPath.replace('\\', '/');
Neil
  • 5,762
  • 24
  • 36