Search code examples
javastringreplaceall

java String manipulation, change multiple slashes to one slash


Silly mistake + is used instead of +

all, I am trying to convert all the "/+ "in input path to "/" to simplify unix - style path.

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

turns out not doing anything, what is the right way of doing this?

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);
 }
}

Solution

  • You're using , not +. It's a different character.

    Replace

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

    with

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