6

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

linuxfan
  • 1,110
  • 2
  • 17
  • 29

1 Answers1

9

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"]