英文:
Get the first directory of a path in GO
问题
在Go语言中,可以通过以下方式获取路径的根目录,使得foo/bar/file.txt
返回foo
。我知道path/filepath
包可以实现,但是下面的代码却打印出了foo/bar/file.txt
和1
,而我本来期望的是foo
和3
。
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")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论