×

go · level 2 · unit 5 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

The can split, join and search your text.

Go comes with a big set of toolboxes called the standard library. You have already used fmt, strings, strconv and sort. Real programs lean on it all the time, so this unit tours some of the most useful parts.

cuts text at every comma and gives a slice: [tea cake toast]. does the opposite. splits at any run of spaces, so messy spacing never matters.

To search, strings.Contains(text, "cake") gives true when the text appears anywhere, and strings.HasPrefix(text, "tea") checks only the start. Together they let you pick apart a line of real data.

package main
import "fmt"
import "strings"
func main() {
	line := "crisps,apple,cake"
	snacks := strings.Split(line, ",")
	fmt.Println(len(snacks), snacks)
	fmt.Println(strings.Join(snacks, " + "))
	fmt.Println(strings.Contains(line, "cake"), strings.HasPrefix(line, "apple"))
	fmt.Println(strings.Fields("  too   many    spaces "))
}

strings.Split keeps empty pieces, so "a,,b" gives three pieces with an empty one in the middle.