go · level 2 · unit 5 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Two spaces between the words. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
import "strings"
func main() {
words := strings.Split("the cat", " ")
fmt.Println(len(words))
fmt.Println(len(strings.Fields("the cat")))
}
your turn
Your turn. Send out the party invites.
Type three friends' names with a comma and no spaces between them, such as Ava,Leo,Sam. The program splits them up, then joins them back together nicely.
output
press run to see what happens
fix it
The scores will not add up. Can you fix it?
output
press run to see what happens
- The program skips the whole line in one go. How many pieces did
Splitmake? - The scores are separated by commas, but line 7 splits at spaces.
- Change " " to "," inside strings.Split on line 7, then run.
nailed it
you can take text apart and rebuild it. :D
- The standard library is the set of toolboxes that comes with Go.
strings.Splitcuts text into a slice, andstrings.Joinglues it back.strings.Fieldssplits at spaces, however many there are.
new words in your collection
- standard library
- strings.Split
- strings.Join
- strings.Fields
This lesson isn’t saved. A free account remembers every lesson you finish.