这可能是一个非常基本的问题,但是在查看字符串包文档后,我无法找到答案。
基本上,我想做的相当于:
echo "hello world" | cut -d" " -f2
echo "hello world" | cut -d" " -f2
这会使用空格作为分隔符拆分字符串"hello world"
,并仅选择第 2 部分(1 索引(。
在 Go for sapting 中,有strings.Split()
返回一个切片,您可以根据需要对其进行索引或切片。
s := "hello world"
fmt.Println(strings.Split(s, " ")[1])
这将输出相同的结果。在Go Playground上尝试一下。如果不能保证输入有 2 个部分,则上述索引 ([1]
( 可能会死机。在执行此操作之前,请检查切片的长度。
有一个strings.Split()
函数,它在指定的子字符串处拆分字符串。
还有Fields(s string) []string
和FieldsFunc(s string, f func(rune) bool) []string
的功能。
前者在空格处拆分字符串,后者使用给定函数来确定是否必须拆分字符串。
Split
和Fields
之间的区别在于,Fields
将多个连续空格视为一个拆分位置。strings.Fields(" foo bar baz "))
产生["foo" "bar" "baz"]
,strings.Split(" foo bar baz ", " ")
产生["" "" "foo" "bar" "" "baz" "" "" ""]
。