有没有像 linux cut 一样工作的 Go 函数?
Is there a Go function that works like linux cut?
这可能是一个非常基本的问题,但在查看 strings 包文档后我还没有找到答案。
基本上,我想做的就是:
echo "hello world" | cut -d" " -f2
echo "hello world" | cut -d" " -f2
这将使用空格作为分隔符来拆分字符串 "hello world"
,并且仅选择第二部分(从 1 开始索引)。
Go for spitting 有 strings.Split()
其中 returns 一个切片,您可以根据需要对其进行索引或切片。
s := "hello world"
fmt.Println(strings.Split(s, " ")[1])
这输出相同。在 Go Playground 上试试吧。如果不能保证输入有 2 个部分,则上述索引 ([1]
) 可能会崩溃。在这样做之前检查切片的长度。
strings.Split()
函数可以在指定的子字符串处拆分字符串。
还有函数Fields(s string) []string
, and 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" "" "" ""]
.
这可能是一个非常基本的问题,但在查看 strings 包文档后我还没有找到答案。
基本上,我想做的就是:
echo "hello world" | cut -d" " -f2
echo "hello world" | cut -d" " -f2
这将使用空格作为分隔符来拆分字符串 "hello world"
,并且仅选择第二部分(从 1 开始索引)。
Go for spitting 有 strings.Split()
其中 returns 一个切片,您可以根据需要对其进行索引或切片。
s := "hello world"
fmt.Println(strings.Split(s, " ")[1])
这输出相同。在 Go Playground 上试试吧。如果不能保证输入有 2 个部分,则上述索引 ([1]
) 可能会崩溃。在这样做之前检查切片的长度。
strings.Split()
函数可以在指定的子字符串处拆分字符串。
还有函数Fields(s string) []string
, and 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" "" "" ""]
.