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?
Asked
Active
Viewed 4.7k times
5
-
1By the way, "\" is a backslash and not a slash. https://secure.wikimedia.org/wikipedia/en/wiki/Backslash – Steve Kuo Apr 22 '11 at 15:26
-
You have no slashes in that string. You have backslashes. – tchrist Apr 22 '11 at 16:18
5 Answers
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
-
3
-
-
1@Cyril - I checked and your answer is correct! Sorry man. I've deleted my stupid comment. – kkaosninja Sep 08 '13 at 05:45