2015-12-09 175 views
1

愚蠢的错误+使用的+Java字符串操作,更改多个斜线一个斜线

一切相反,我试图把所有的“/ +”输入路径为‘/’,以简化UNIX - 风格的路径。

path.replaceAll("/+", "/"); 
path.replaceAll("\\/+", "/"); 

原来没有做任何事情,这样做的正确方法是什么?

public class SimplifyPath { 
public String simplifyPath(String path) { 
    Stack<String> direc = new Stack<String>(); 
    path = path.replaceAll("/+", "/"); 
    System.out.println("now path becomes " + path); // here path remains "///" 

    int i = 0; 
    while (i < path.length() - 1) { 
     int slash = path.indexOf("/", i + 1); 
     if (slash == -1) break; 
     String tmp = path.substring(i, slash); 
     if (tmp.equals("/.")){ 
      continue; 
     } else if (tmp.equals("/..")) { 
      if (! direc.empty()){ 
       direc.pop(); 
      } 
      return "/"; 
     } else { 
      direc.push(tmp); 
     } 
     i = slash; 
    } 
    if (direc.empty()) return "/"; 
    String ans = ""; 
    while (!direc.empty()) { 
     ans = direc.pop() + ans; 
    } 
    return ans; 
} 

public static void main(String[] args){ 
    String input = "///"; 
    SimplifyPath test = new SimplifyPath(); 
    test.simplifyPath(input); 
} 
} 
+1

尝试path.replaceAll( “\\/+”, “/”); – Berger

+0

这不工作,这是一个Java版本的问题? – javarookie

回答

6

您使用的是而不是+。这是一个不同的性格。

更换

path = path.replaceAll("/+", "/"); 

path = path.replaceAll("/+", "/"); 
-1

您在使用文件分割符...这是较安全\审判或/因为Linux和Windows使用不同的文件分隔符。使用File.separator将使程序运行,而不管它运行的平台是什么,毕竟这是JVM的要点。 - 正斜杠将起作用,然而,File.separator会让最终用户更有信心。 例如,对于路径: “测试/世界”

String fileP = "Test" + File.separator + "World"; 
+0

此用户有[抄袭](http://meta.stackexchange.com/questions/160077/users-are-calling-me-a-plagiarist-what-do-i-do)这个答案:http:// stackoverflow的.com /一个/ 24643179 – BalusC

0

所以,你要//一// B // C转换为/ A/B/C?

public static void main(String[] args) { 
    String x = "///a//b//c"; 
    System.out.println(x.replaceAll("/+", "/")); 
} 

应该诀窍。

事实上,如果你想/ + - > /转换你需要躲避+,而不是/

public static void main(String[] args) { 
    String x = "/+/+/a//b/+/c"; 
    System.out.println(x.replaceAll("/\\+", "/")); 
}