Start learning free

LESSON 65 OF 671 · STRINGS I

String Split in Go

Lesson

In Go, you can split a string into a slice of strings with strings.Split(s, sep), which cuts the string at every occurrence of the separator sep:

// strings.Split() cuts a string at every separator
sentence := "hello world foo"
words := strings.Split(sentence, " ")
// words == []string{"hello", "world", "foo"}

Two spaces in a row give an empty string between them: strings.Split("a b", " ") is []string{"a", "", "b"}. To split on any run of whitespace and skip the empty pieces, use strings.Fields(s) instead.


Assignment
Follow the Coding Tutorial and split sentence at every space into a slice of words!


Hint
Use strings.Split(sentence, " ") and assign the result to words.

STEP 1 OF 1
    Ctrl + Enter to check