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,885 questions

51,811 answers

573 users

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

1 Answer

0 votes
package main

import (
    "fmt"
    "strings"
)

// Function to simplify a Unix-style file path
func simplifyPath(path string) string {
    var stack []string       // Slice used as a stack to store valid directory names
    result := ""             // Final simplified path
    psize := len(path)       // Length of the input path
    i := 0

    // Iterate through each character in the path
    for i < psize {
        if path[i] == '/' {
            i++
            continue // Skip redundant slashes
        }

        var pathpart strings.Builder

        // Extract the next pathpart until the next slash
        for i < psize && path[i] != '/' {
            pathpart.WriteByte(path[i])
            i++
        }

        part := pathpart.String()

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

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

        // Valid pathpart, push to stack
        stack = append(stack, part)
    }

    // Reconstruct the simplified path from the stack
    for len(stack) > 0 {
        n := len(stack)
        result = "/" + stack[n-1] + result
        stack = stack[:n-1] // Pop from stack
    }

    // If the stack was empty, return root directory
    if result == "" {
        return "/"
    }

    return result
}

func main() {
    // Input path to be simplified
    inputPath := "/home//foo/../bar/./unix/"

    simplified := simplifyPath(inputPath)

    fmt.Println("Simplified path:", simplified)
}



/*
run:

Simplified path: /home/foo/bar/unix

*/

 



answered Sep 9, 2025 by avibootz
...