Skip to content

Latest commit

 

History

History
22 lines (13 loc) · 936 Bytes

split-a-string-on-whitespace-in-go.md

File metadata and controls

22 lines (13 loc) · 936 Bytes

字符串如果通过空格分割转换为数组

stackoverflow连接

原本我是想用strings.Split这个方法的,但这个方法明显有问题,当空格个数不是1个时,它会把两个空格中间的空串也作为一个值,所以用strings.Split来分割"aa   bb"这种情况是不正确的。

正确的方法是使用strings.Fields方法,代码如下:

someString := "one    two   three four "

words := strings.Fields(someString)

fmt.Println(words, len(words)) // [one two three four] 4

官方文档连接

func Fields(s string) []string

Fields 方法通过判断字符串 s 中 一个或多个连续空格字符作为依据进行拆分,返回一个字符串数组,或当字符串只包含空格时返回一个空数组。