150

给定一个输入字符串,例如" word1 word2 word3 word4 ",在 Go 中将其拆分为字符串数组的最佳方法是什么?请注意,每个单词之间可以有任意数量的空格或 unicode-spacing 字符。

在 Java 中,我只会使用someString.trim().split("\\s+").

(注意:在 Go 中使用正则表达式可能出现重复的拆分字符串并不能提供任何高质量的答案。请提供一个实际示例,而不仅仅是指向regexpstrings包参考的链接。)

4

4 回答 4

319

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

Fieldss围绕一个或多个连续空白字符的每个实例拆分字符串,s如果 s 仅包含空白,则返回一个子字符串数组或一个空列表。

于 2012-12-06T06:05:38.437 回答
11

如果您使用提示:regexp.Split

func (re *Regexp) Split(s string, n int) []string

将切片 s 拆分为由表达式分隔的子字符串,并返回这些表达式匹配之间的子字符串切片。

此方法返回的切片由不包含在 FindAllString 返回的切片中的 s 的所有子字符串组成。当在不包含元字符的表达式上调用时,它等效于 strings.SplitN。

例子:

s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
// s: ["", "b", "b", "c", "cadaaae"]

计数确定要返回的子字符串的数量:

n > 0: at most n substrings; the last substring will be the unsplit remainder.
n == 0: the result is nil (zero substrings)
n < 0: all substrings
于 2012-12-06T06:35:06.607 回答
6

我想出了以下内容,但这似乎有点过于冗长:

import "regexp"
r := regexp.MustCompile("[^\\s]+")
r.FindAllString("  word1   word2 word3   word4  ", -1)

这将评估为:

[]string{"word1", "word2", "word3", "word4"}

有没有更紧凑或更惯用的表达方式?

于 2012-12-06T05:53:12.283 回答
1

您可以使用包字符串函数 split strings.Split(someString, " ")

字符串.Split

于 2020-12-26T03:04:50.673 回答