1

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);
 }
}
sthbuilder
  • 561
  • 1
  • 7
  • 22

3 Answers3

7

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

Replace

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

with

path = path.replaceAll("/+", "/");
dejvuth
  • 6,986
  • 3
  • 33
  • 36
0

So you want //a//b//c to be converted to /a/b/c ?

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

Should to the trick.

If in fact you want /+ -> / conversion you'd need to escape the +, not the /

public static void main(String[] args) {
    String x = "/+/+/a//b/+/c";
    System.out.println(x.replaceAll("/\\+", "/"));
}
Jan
  • 13,738
  • 3
  • 30
  • 55
-1

Have you tried using File.separator ... This is safer than \ or / because Linux and Windows use different file separators. Using File.separator will make your program run regardless of the platform it is being run on, after all, that is the point of the JVM. -- forward slash will work, however, File.separator will make you end users more confident that it will. For example for the path : "Test/World"

String fileP = "Test" + File.separator + "World";
Haseeb Anser
  • 494
  • 1
  • 5
  • 19
  • This user has [plagiarized](http://meta.stackexchange.com/questions/160077/users-are-calling-me-a-plagiarist-what-do-i-do) this answer: http://stackoverflow.com/a/24643179 – BalusC Dec 14 '15 at 16:12