go - 获取类似 python 的 split() 与 go 的 strings.Split() 一起工作

标签 go split

<分区>

在 python 中,没有分隔符的 split() 函数会拆分空白/制表符等,并返回一个列表,其中所有 空格被移除

>>> "string    with multiple      spaces".split()
['string', 'with', 'multiple', 'spaces']

如何在 go 中实现类似的功能?

package main

import "fmt"
import "strings"

func main() {
    s := "string    with multiple      spaces"
    lst := strings.Split(s, " ")
    for k, v := range lst {
        fmt.Println(k,v)
    }
}

上面给出了

0 string
1 
2 
3 
4 with
5 multiple
6 
7 
8 
9 
10 
11 spaces

我想将每个字符串保存在 lst[0]lst[1]lst[2]lst[3]。这可以做到吗?谢谢

最佳答案

您正在寻找strings.Fields :

func Fields(s string) []string

Fields splits the string s around each instance of one or more consecutive white space characters, as defined by unicode.IsSpace, returning an array of substrings of s or an empty list if s contains only white space.

Example

fmt.Printf("Fields are: %q", strings.Fields("  foo bar  baz   "))

Output:

Fields are: ["foo" "bar" "baz"]

关于go - 获取类似 python 的 split() 与 go 的 strings.Split() 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30221933/

相关文章:

go - 如何编码 XML

java - 通过标签java分割字符串

去正确的行为,或编译器错误?

goroutine 上下文取消 panic

java - 正则表达式模式,匹配器,split或pattern.split()哪个是最有效的

mysql - 每 5 个字符分割一个字符串并获得不同的字符串

java - 用java分割字符串不起作用

mysql - 分割行字段mysql创建新列

entity-system - ECS with Go - 循环导入

go - 从单独的文件夹加载模型时如何解决 `import cycle not allowed`