How to simplify path (remove ".." and "." and replace multiple “////” with one single “/”) in Swift

1 Answer

0 votes
import Foundation

// Function to simplify a Unix-style file path
func simplifyPath(_ path: String) -> String {
    var stack: [String] = []     // Stack to hold valid directory names
    var result = ""              // Final simplified path
    let chars = Array(path)      // Work with Character array for index access
    let psize = chars.count      // Length of the input path
    var i = 0

    // Iterate through each character in the path
    while i < psize {
        if chars[i] == "/" {
            i += 1
            continue  // Skip redundant slashes
        }

        var pathpart = ""

        // Extract the next pathpart until the next slash
        while i < psize && chars[i] != "/" {
            pathpart.append(chars[i])
            i += 1
        }

        // Ignore current directory references
        if pathpart == "." {
            continue
        }
        // Ignore parent directory references (no popping here)
        else if pathpart == ".." {
            continue
        }
        // Valid directory name, push to stack
        else {
            stack.append(pathpart)
        }
    }

    // Reconstruct the simplified path from the stack
    while !stack.isEmpty {
        result = "/" + (stack.removeLast()) + result
    }

    // If the stack was empty, return root directory
    return result.isEmpty ? "/" : result
}

// Input path to be simplified
let inputPath = "/home//foo/../bar/./unix/"

// Call the simplifyPath function
let simplified = simplifyPath(inputPath)

// Output the result
print("Simplified path: \(simplified)")



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 9, 2025 by avibootz
...