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);
 }
}
2
  • 1
    Try path.replaceAll( "\\/+", "/"); Commented Dec 9, 2015 at 9:11
  • this not working either, is this a java version issue ? Commented Dec 9, 2015 at 9:14

3 Answers 3

7

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

Replace

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

with

path = path.replaceAll("/+", "/");
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

-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";

1 Comment

This user has plagiarized this answer: stackoverflow.com/a/24643179

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.