java字符串操作,将多个斜杠更改为一个斜杠

sth*_*der 1 java string replaceall

愚蠢的错误+用来代替+

所有,我试图将输入路径中的所有"/ +"转换为"/"以简化unix风格的路径.

 path.replaceAll( "/+", "/"); 
 path.replaceAll( "\\/+", "/"); 
Run Code Online (Sandbox Code Playgroud)

事实证明没有做任何事情,这样做的正确方法是什么?

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);
 }
}
Run Code Online (Sandbox Code Playgroud)

dej*_*uth 6

你正在使用?,而不是+.这是一个不同的角色.

更换

path = path.replaceAll("/?", "/");
Run Code Online (Sandbox Code Playgroud)

path = path.replaceAll("/+", "/");
Run Code Online (Sandbox Code Playgroud)