Home > Net >  Easiest way to split file system path into segments/sections
Easiest way to split file system path into segments/sections

Time:09-19

I want to create a list of segments from a file system path in golang.

  • On Windows: "a\b\c" should get parsed to ["a", "b", "c"]
  • On POSIX systems: "a/b/c" should get parsed to ["a", "b", "c"]

Looking at the path/filepath package I can only see the Split function, which only splits the path into two strings, the last segment and everything else.

Is there any standard library function that would split the path into all segments out of the box?

I can think of this workaround:

strings.Split(filepath.ToSlash(path), "/")

I was also thinking about using filepath.Split, recursively, but it ends up in an infinite loop, because the dir string contains the ending separator. See this example to understand why can't you run Split multiple times https://go.dev/play/p/xZ-2DML0xWK.

func mySplit(path string) []string {
    dir, last := filepath.Split(path)
    if dir == "" {
        return []string{last}
    }
    return append(mySplit(dir), last)
}

CodePudding user response:

r := strings.Split("a/b/c", "/")

CodePudding user response:

Clean before split.

func mySplit(path string) []string {
    dir, last := filepath.Split(path)
    if dir == "" {
        return []string{last}
    }
    return append(mySplit(filepath.Clean(dir)), last)
}
  • Related