给定输入字符串,例如" word1 word2 word3 word4"
,在Go中将其拆分为字符串数组的最佳方法是什么?请注意,每个单词之间可以有_任意_数量的空格或Unicode空格字符。
在Java中,我只会使用someString.trim().split("\\s+")
。
(注意:在Go中使用正则表达式可能重复的Split字符串不会给出任何高质量的答案。请提供实际示例,而不仅仅是提供指向regexp
或strings
包引用的链接。)
所述strings
封装具有一个Fields
方法。
someString := "one two three four "
words := strings.Fields(someString)
fmt.Println(words, len(words)) // [one two three four] 4
演示: http :
//play.golang.org/p/et97S90cIH
从文档:
func Fields(s string) []string
字段在
s
一个或多个连续的空白字符的每个实例周围拆分字符串,s
如果s仅包含空格,则返回的子字符串数组或一个空列表。