在Java中,我有一个文件路径,例如'C:\A\B\C',我想将其更改为'C:/A/B/C'。如何替换反斜杠?
String text = "C:\\A\\B\\C";
String newString = text.replace("\\", "/");
System.out.println(newString);
由于您需要一个正则表达式,因此您需要多次转义“\”字符:
String path = "c:\\A\\B\\C";
System.out.println(path.replaceAll("\\\\", "/"));
public static void main(String[] args) {
String foo = "C:\\foo\\bar";
String newfoo = foo.replace("\\", "/");
System.out.println(newfoo);
}
要替换所有出现的给定字符:
String result = candidate.replace( '\\', '/' );
祝好, Cyril
'\\'
代替'\'
。 - Ted HoppString oldPath = "C:\\A\\B\\C";
String newPath = oldPath.replace('\\', '/');