Drill

ProblemsC# › patterns

Tidy up a file path

hardpatternsStacksStringsParsingC#

A storage service is handed paths with stray slashes and dot segments in them, and stores exactly one canonical form.

TidyPath(raw: string) → string

C# needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.

Solve it in Python →

Where you start

public string TidyPath(string raw) {
    
}

Worked examples

CallResult
TidyPath("/home//user/")"/home/user"
TidyPath("/a/./b/../c")"/a/c"
TidyPath("/../")"/"
TidyPath("/")"/"

Hint

Split on the slash and push each real segment onto a stack; ".." pops instead. Joining the stack back up gives the answer.

Reference solution in C#
public string TidyPath(string raw) {
    var kept = new List<string>();
    foreach (var part in raw.Split('/')) {
        if (part.Length == 0 || part == ".") continue;
        if (part == "..") {
            if (kept.Count > 0) kept.RemoveAt(kept.Count - 1);
        } else {
            kept.Add(part);
        }
    }
    return "/" + string.Join("/", kept);
}

The same problem in another language

More patterns problems in C#