获取GO中路径的第一个目录。

huangapple go评论96阅读模式
英文:

Get the first directory of a path in GO

问题

在Go语言中,可以通过以下方式获取路径的根目录,使得foo/bar/file.txt返回foo。我知道path/filepath包可以实现,但是下面的代码却打印出了foo/bar/file.txt1,而我本来期望的是foo3

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	parts := filepath.SplitList("foo/bar/file.txt")
	fmt.Println(parts[0])
	fmt.Println(len(parts))
}
英文:

In Go, is it possible to get the root directory of a path so that

returns foo? I know about path/filepath, but

package main

import (
        "fmt"
        "path/filepath"
)

func main() {
        parts := filepath.SplitList("foo/bar/file.txt")
        fmt.Println(parts[0])
        fmt.Println(len(parts))
}

prints foo/bar/file.txt and 1 whereas I would have expected foo and 3.

答案1

得分: 18

简单地使用strings.Split()函数:

s := "foo/bar/file.txt"
parts := strings.Split(s, "/")
fmt.Println(parts[0], len(parts))
fmt.Println(parts)

输出结果(在Go Playground上尝试):

foo 3
[foo bar file.txt]

注意:

如果你想按照当前操作系统的路径分隔符进行分割,可以使用os.PathSeparator作为分隔符:

parts := strings.Split(s, string(os.PathSeparator))

filepath.SplitList()函数将多个连接的路径分割为单独的路径。它不会将一个路径分割为文件夹和文件。例如:

fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin"))

输出结果:

On Unix: [/a/b/c /usr/bin]
英文:

Simply use strings.Split():

s := "foo/bar/file.txt"
parts := strings.Split(s, "/")
fmt.Println(parts[0], len(parts))
fmt.Println(parts)

Output (try it on the Go Playground):

foo 3
[foo bar file.txt]

Note:

If you want to split by the path separator of the current OS, use os.PathSeparator as the separator:

parts := strings.Split(s, string(os.PathSeparator))

filepath.SplitList() splits multiple joined paths into separate paths. It does not split one path into folders and file. For example:

fmt.Println("On Unix:", filepath.SplitList("/a/b/c:/usr/bin"))

Outputs:

On Unix: [/a/b/c /usr/bin]

答案2

得分: 3

请注意,根据我的测试,如果你只需要第一部分,使用strings.SplitN至少比较快10倍:

package main
import "strings"

func main() {
   parts := strings.SplitN("foo/bar/file.txt", "/", 2)
   println(parts[0] == "foo")
}

https://golang.org/pkg/strings#SplitN

英文:

Note that if you just need the first part, strings.SplitN is at least 10 times
faster from my testing:

package main
import "strings"

func main() {
   parts := strings.SplitN("foo/bar/file.txt", "/", 2)
   println(parts[0] == "foo")
}

https://golang.org/pkg/strings#SplitN

huangapple
  • 本文由 发表于 2015年11月10日 05:53:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/33618967.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定