Skip to content

Instantly share code, notes, and snippets.

@raylax
Created November 17, 2021 07:53
Show Gist options
  • Save raylax/6c407f782fb4f1c62ec4064d55ce62b0 to your computer and use it in GitHub Desktop.
Save raylax/6c407f782fb4f1c62ec4064d55ce62b0 to your computer and use it in GitHub Desktop.
public static String normalize(String text) {
StringBuilder sb = new StringBuilder();
int ci;
int pi = -1;
while ((ci = text.indexOf('/', pi + 1)) != -1) {
if (ci == 0) {
sb.append('/');
} else {
String s = text.substring(pi + 1, ci);
if (s.equals("..")) {
int end;
if (sb.length() > 1 && (end = sb.lastIndexOf("/")) != -1) {
int start = sb.lastIndexOf("/", end - 1);
sb.delete(Math.max(start, 0), end);
}
} else if (!s.isEmpty() && !s.equals(".")) {
sb.append(s);
sb.append('/');
}
}
pi = ci;
}
if (pi > 1) {
sb.append(text.substring(pi + 1));
}
return sb.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment