愚蠢的錯誤+使用的+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);
}
}
嘗試path.replaceAll( 「\\/+」, 「/」); – Berger
這不工作,這是一個Java版本的問題? – javarookie