Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,926 questions

51,859 answers

573 users

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

1 Answer

0 votes
// Function to simplify a Unix-style file path
fn simplify_path(path: &str) -> String {
    let mut stack: Vec<String> = Vec::new(); // Stack to store valid directory names
    let psize = path.len();                  // Length of the input path
    let bytes = path.as_bytes();
    let mut i: usize = 0;

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

        let mut part_bytes: Vec<u8> = Vec::new();

        // Extract the next pathpart until the next slash
        while i < psize && bytes[i] != b'/' {
            part_bytes.push(bytes[i]);
            i += 1;
        }

        let pathpart = String::from_utf8(part_bytes).unwrap_or_default();

        // Ignore current pathpart references
        if pathpart == "." {
            continue;
        }

        // Handle parent pathpart reference
        else if pathpart == ".." {
            // Ignore ".." instead of popping
            continue;
        }

        // Valid pathpart, push to stack
        else if !pathpart.is_empty() {
            stack.push(pathpart);
        }
    }

    // Reconstruct the simplified path from the stack
    if stack.is_empty() {
        // If the stack was empty, return root directory
        "/".to_string()
    } else {
        format!("/{}", stack.join("/"))
    }
}

fn main() {
    // Input path to be simplified
    let input_path = "/home//foo/../bar/./unix/";

    let simplified = simplify_path(input_path);

    println!("Simplified path: {}", simplified);
}



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 9, 2025 by avibootz
...