内容简介:将字符串分解为单词可能很棘手。首先,确定单词是什么,以及分隔符是什么,以及是否有任何空格或任何其他字符。做出这些决定后,你可以从strings包中选择适当的功能。
将字符串分解为单词可能很棘手。首先,确定单词是什么,以及分隔符是什么,以及是否有任何空格或任何其他字符。做出这些决定后,你可以从strings包中选择适当的功能。
将字符串分解为单词
Golang 版本
1.12.1
前言
将字符串分解为单词可能很棘手。首先,确定单词是什么,以及分隔符是什么,以及是否有任何空格或任何其他字符。做出这些决定后,你可以从strings包中选择适当的功能。
实现
-
创建文件
whitespace.go
,代码如下:package main import ( "fmt" "strings" ) const refString = "Mary had a little lamb" func main() { words := strings.Fields(refString) for idx, word := range words { fmt.Printf("Word %d is: %s\n", idx, word) } }
$ go run whitespace.go 单词 0 是: Mary 单词 1 是: had 单词 2 是: a 单词 3 是: little 单词 4 是: lamb
-
创建文件
anyother.go
,代码如下:package main import ( "fmt" "strings" ) const refString = "Mary_had a little_lamb" func main() { words := strings.Split(refString, "_") for idx, word := range words { fmt.Printf("单词 %d 是: %s\n", idx, word) } }
$ go run anyother.go 单词 0 是: Mary 单词 1 是: had a little 单词 2 是: lamb
-
创建文件
specfunction.go
,代码如下:package main import ( "fmt" "strings" ) const refString = "Mary*had,a%little_lamb" func main() { // 为字符串中的每个符文调用splitFunc。如果符文等于“*%,_”中的任何字符,则拆分refString splitFunc := func(r rune) bool { return strings.ContainsRune("*%,_", r) } words := strings.FieldsFunc(refString, splitFunc) for idx, word := range words { fmt.Printf("单词 %d 是: %s\n", idx, word) } }
$ go run specfunction.go 单词 0 是: Mary 单词 1 是: had 单词 2 是: a 单词 3 是: little 单词 4 是: lamb
-
创建文件
regex.go
,代码如下:package main import ( "fmt" "regexp" ) const refString = "Mary*had,a%little_lamb" func main() { words := regexp.MustCompile("[*,%_]{1}").Split(refString, -1) for idx, word := range words { fmt.Printf("单词 %d 是: %s\n", idx, word) } }
$ go run regex.go 单词 0 是: Mary 单词 1 是: had 单词 2 是: a 单词 3 是: little 单词 4 是: lamb
原理
将字符串分割成单词的最简单形式是将任何空格作为分隔符。其中空格由 unicode
包中的 IsSpace
函数定义:
‘\t’, ‘\n’, ‘\v’, ‘\f’, ‘\r’, ‘ ‘, U+0085 (NEL), U+00A0 (NBSP).
如前所述, string
包的 Fields
函数可用于空格字符分割句子。步骤1涵盖了第一个简单的案例。
如果需要其他分隔符,则使用 Split
函数。在步骤2中讨论了用另一个分隔符进行分割。请注意,字符串中的空格被省略了。
如果需要一个更复杂的函数来决定是否在给定的位置拆分字符串, FieldsFunc
可以为你提供帮助。该函数的一个参数是使用给定字符串的符文并返回 true
(如果该字符串在该点应该分割)的函数。这个选项包含在步骤3中。
正则表达式是示例中提到的最后一个选项。 Regexp
包的 Regexp
结构体包含 Split
方法,其工作方式与您所期望的一样。它将字符串分割到匹配组的位置。此方法在步骤4中使用。
延伸
该 strings
包还提供各种 SplitXXX
功能,可以帮助你实现更具体的任务。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
An Introduction to Probability Theory and Its Applications
William Feller / Wiley / 1991-1-1 / USD 120.00
Major changes in this edition include the substitution of probabilistic arguments for combinatorial artifices, and the addition of new sections on branching processes, Markov chains, and the De Moivre......一起来看看 《An Introduction to Probability Theory and Its Applications》 这本书的介绍吧!