go · level 1 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
The strings toolbox is full of tricks for text.
counts the characters in a string, spaces included, so len("cat") is 3. For more tricks, add a second line, import "strings", to bring in the strings toolbox.
makes every letter a capital, and strings.ToLower makes them small. snips spaces off both ends. swaps every copy of one piece of text for another.
None of these change your box. They hand back a new string, so store it if you want to keep it: name = strings.TrimSpace(name).
package main
import "fmt"
import "strings"
func main() {
shout := " hello there "
fmt.Println(len(shout))
fmt.Println(strings.ToUpper(shout))
fmt.Println(strings.TrimSpace(shout))
fmt.Println(strings.ReplaceAll("cats and cats", "cats", "dogs"))
} Each toolbox gets its own import line at the top, under package main.
guess first
Count carefully. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
fmt.Println(len("ice cream"))
}
your turn
Your turn. Crown a champion.
Type a name in the box, in small letters if you like. strings.ToUpper will shout it for you.
output
press run to see what happens
fix it
The spaces will not go away. Can you fix it?
output
press run to see what happens
- Read the error on line 6. Go says the result of TrimSpace is not used.
- TrimSpace hands back a tidy new string, but nothing catches it. Store it in the box.
- Change line 6 to answer = strings.TrimSpace(answer), then press run.
nailed it
you learned some tricks with text. :D
lencounts the characters in a string.- Import
stringsforToUpper,ToLower,TrimSpaceandReplaceAll. - These hand back a new string, so store it.
new words in your collection
- len
- ToUpper
- TrimSpace
- ReplaceAll
This lesson isn’t saved. A free account remembers every lesson you finish.