Go Reference ยท strings and strconv
Go strings.Fields() function
Reference for Go strings.Fields, FieldsFunc and FieldsSeq: split text on runs of whitespace or a custom rule, with no empty pieces, and how it differs from Split.
strings.Fields(s) splits s around runs of white space (as defined by unicode.IsSpace) and returns the words in between. Leading, trailing and repeated white space never produce empty strings, which makes it the right tool for tokenizing human-typed text.
FieldsFunc lets you decide what counts as a separator with your own function, and FieldsSeq and FieldsFuncSeq (Go 1.24) return iterators.
words := strings.Fields(" go is\tfun\n") // ["go" "is" "fun"]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Fields(s string) []string func FieldsFunc(s string, f func(rune) bool) []string func FieldsSeq(s string) iter.Seq[string] func FieldsFuncSeq(s string, f func(rune) bool) iter.Seq[string]
| Name | Description |
|---|---|
s |
The text to split. |
f |
Returns true for runes that are separators. Must be a pure function: results should not depend on call order. |
Returns: a slice of non-empty substrings, in order. If s has only white space or is empty, the slice is empty (length 0).
Edge cases: any Unicode space (tab, newline, form feed, non-breaking space U+00A0, U+2003 and so on) counts as a separator for Fields. FieldsSeq and FieldsFuncSeq need Go 1.24 or newer.
Usage notes
FieldsvsSplit(s, " "):Splitkeeps empty pieces between neighbouring spaces and does not know about tabs or newlines. For free-form text,Fieldsis almost always what you want.- Counting words is
len(strings.Fields(s)). It treats punctuation as part of a word; useFieldsFuncif"hello,"should become"hello". - Pieces share memory with
s, likeSplit. - Parsing columns: for command-line style input with quotes,
Fieldsis not enough; use a proper tokenizer or theencoding/csvreader with a custom delimiter. - Performance:
Fieldsmakes one pass to count and one to slice, so it is efficient, but the iterator variants avoid the slice allocation. - Fixed separators with empties preserved (
a,,b): usestrings.Split()instead. - Inverse:
strings.Join(words, " ")rebuilds text with single spaces, which normalizes spacing.