Get python-like split() working with go's strings.Split()

huangapple go评论70阅读模式
英文:

Get python-like split() working with go's strings.Split()

问题

在Python中,没有指定分隔符的split()函数会根据空格、制表符等进行分割,并返回一个移除了所有空格的列表。

如何在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]中的每个字符串保存起来。这可以实现吗?谢谢。

英文:

In python, the split() function with no separator splits the on whitespace/tab etc. and returns a list with all spaces removed

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

How can I achieve something similar in 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)
	}
}

The above gives

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

I'd like to save each of the strings in lst[0], lst[1], lst[2] and lst[3]. Can this be done? Thanks

答案1

得分: 9

你正在寻找strings.Fields函数:

> func Fields(s string) []string
> Fields函数将字符串s按照一个或多个连续的空白字符进行分割,空白字符的定义由unicode.IsSpace确定,返回s的子字符串数组,如果s只包含空白字符,则返回空列表。
>
> 示例
>
> fmt.Printf("Fields are: %q", strings.Fields(" foo bar baz "))
> 输出:
>
> Fields are: ["foo" "bar" "baz"]

英文:

You are looking for 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"]

huangapple
  • 本文由 发表于 2015年5月14日 01:47:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/30221933.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定