回答

收藏

在 Go 中在空格上拆分字符串?

技术问答 技术问答 229 人阅读 | 0 人回复 | 2023-09-12

给定输入字符串,例如"  word1   word2 word3   word4  ",在 Go 将其分成字符串数组的最佳方法是什么?请注意,每个单词之间都可以有任意数量空间或 unicode-spacing 字符。
% J, E+ K* G& v* T4 R; _6 r3 k/ ~在 Java 中,我只能用someString.trim().split("\\s ").: l, q: v1 D/ \. T4 E2 V% w# c2 v
                                                                ( V  D" D) E" W) l
    解决方案:                                                                0 g0 n/ ~. D+ A  T. Z
                                                                该strings包有一个Fields方法。
) K" I8 V5 }" `* S
    someString := "one    two   three four "words := strings.Fields(someString)fmt.Println(words,len(words)) // [one two three four] 48 m" _/ `4 g& H5 A  ^; E. o
演示:    http :    //play.golang.org/p/et97S90cIH( ]5 o5 {2 \4 e) b% m% ^& \4 L2 K3 }
从文档:9 ]4 _( L+ M* P! N4 [7 M$ v
func Fields(s string) []string7 V0 b: \4 D+ Q7 O/ W
字段s每个实例围绕一个或多个连续空格字符拆分字符串,s如果 s 如果只包含空间,则返回 子字符串数组或空列表。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则