The strings Package
Many jobs with text come up again and again: change the case, find a word, split a line into parts. Go has ready-made functions for these in the strings package. To use them, add "strings" to the imports, next to "fmt":
package main
import (
"fmt"
"strings"
)
func main() {
title := "Go is Fun"
fmt.Println(strings.ToUpper(title))
fmt.Println(strings.ToLower(title))
fmt.Println(title)
}
Output:
GO IS FUN
go is fun
Go is Fun
Look at the last line. title did not change. These functions never change the string you pass in. They return a new string, and you print it or store it in a variable. The Building Strings lesson explains why.
Searching
These functions look for some text inside a string:
file := "report-2024.txt"
fmt.Println(strings.Contains(file, "2024"))
fmt.Println(strings.Index(file, "-"))
fmt.Println(strings.Index(file, "#"))
fmt.Println(strings.HasPrefix(file, "rep"))
fmt.Println(strings.HasSuffix(file, ".pdf"))
Output:
true
6
-1
true
false
Contains tells you if the text is anywhere in the string. Index gives the byte index where the text starts, or -1 when it is not there. Here the - is at index 6, and there is no #. HasPrefix checks the start of the string, and HasSuffix checks the end. All of them care about case: "Go" and "go" are different.
Replacing
strings.ReplaceAll replaces every match. strings.Replace takes one more number: how many matches to replace, counting from the left:
date := "2024-05-17"
fmt.Println(strings.ReplaceAll(date, "-", "/"))
fmt.Println(strings.Replace(date, "-", "/", 1))
Output:
2024/05/17
2024/05-17
Splitting and joining
strings.Split cuts a string at every separator and gives you a slice. Two separators in a row give an empty part. The %q verb prints each string in quotes, so you can see the empty one:
parts := strings.Split("red,green,,blue", ",")
fmt.Println(len(parts))
fmt.Printf("%q\n", parts)
Output:
4
["red" "green" "" "blue"]
To split at spaces, use strings.Fields. It splits at any run of spaces, so it never gives empty parts. strings.Join does the opposite of splitting: it glues a slice of strings together with a separator between them:
words := strings.Fields(" one two three ")
fmt.Printf("%q\n", words)
fmt.Println(strings.Join(words, "-"))
Output:
["one" "two" "three"]
one-two-three
Trimming and repeating
strings.TrimSpace removes spaces at the start and the end. The brackets show where the string begins and ends. strings.Repeat writes a string several times:
name := " Alice "
fmt.Println("[" + strings.TrimSpace(name) + "]")
fmt.Println(strings.Repeat("=-", 5))
Output:
[Alice]
=-=-=-=-=-
Strings and numbers together
The Type Conversion lesson showed strconv.Atoi, which turns text into an int, and strconv.Itoa, which does the opposite. They come from the strconv package, not from strings, so this program imports all three. Together with Split, they can add up numbers written in one string:
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
parts := strings.Split("4,8,x,15", ",")
total := 0
for _, p := range parts {
n, err := strconv.Atoi(p)
fmt.Println(p, n, err)
total += n
}
fmt.Println("total: " + strconv.Itoa(total))
}
Output:
4 4 <nil>
8 8 <nil>
x 0 strconv.Atoi: parsing "x": invalid syntax
15 15 <nil>
total: 27
The part x is not a number, so Atoi gave 0 and an error. The 0 added nothing, so the total is 27. But often a bad part means the input is wrong, and the program should notice. A real program checks err and decides what to do. The Returning Errors lesson shows how.
In the exercise, split a line of words at the commas, skip the empty parts, change the words to lower case, join them back together and print how many there are.