I H*_*azy 212
所述strings封装具有一个Fields方法.
someString := "one two three four "
words := strings.Fields(someString)
fmt.Println(words, len(words)) // [one two three four] 4
Run Code Online (Sandbox Code Playgroud)
演示: http : //play.golang.org/p/et97S90cIH
来自文档:
func Fields(s string) []stringFields将字符串拆分
s为一个或多个连续空格字符的每个实例,s如果s仅包含空格,则返回子字符串数组或空列表.
如果你正在使用tip:regexp.Split
func (re *Regexp) Split(s string, n int) []string
Run Code Online (Sandbox Code Playgroud)
将切片拆分为由表达式分隔的子字符串,并返回这些表达式匹配之间的子字符串切片.
此方法返回的切片由未包含在FindAllString返回的切片中的s的所有子字符串组成.当调用不包含元字符的表达式时,它等同于strings.SplitN.
例:
s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
// s: ["", "b", "b", "c", "cadaaae"]
Run Code Online (Sandbox Code Playgroud)
计数确定要返回的子字符串数:
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
Run Code Online (Sandbox Code Playgroud)
我想出了以下内容,但这似乎有点太冗长了:
import "regexp"
r := regexp.MustCompile("[^\\s]+")
r.FindAllString(" word1 word2 word3 word4 ", -1)
Run Code Online (Sandbox Code Playgroud)
这将评估为:
[]string{"word1", "word2", "word3", "word4"}
Run Code Online (Sandbox Code Playgroud)
有没有更简洁或更惯用的表达方式?
| 归档时间: |
|
| 查看次数: |
57927 次 |
| 最近记录: |