2015-12-09 173 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("/\\+", "/")); 
}