DMarlon Studio

Lesson 17 · 17 of 20

The strings and strconv packages · Go

Work with text in Go using the strings package (Split, TrimSpace, Join, Contains, Replace) and convert text and numbers with strconv.

Go · The strings and strconv packages in DMarlon Studio: the example's code and its output in the terminal

The `strings` package holds the functions for working with text. strings.Split(line, ",") cuts the shopping list at each comma and returns a slice. The pieces carry extra spaces, which strings.TrimSpace removes from both ends; %q shows them in quotes so you can check.

Go strings cannot be modified: these functions return a new string and leave the original as it was. That is why parts[i] = strings.TrimSpace(parts[i]) stores the result back in the slice.

strings.Join does the opposite of Split: it joins the slice with the separator you give it, here " | ". ToUpper turns text into capitals, Contains says whether one string contains another, Replace substitutes (the 1 says how many times; -1 would mean all), Count counts occurrences and Repeat repeats a string, handy for drawing a line.

The `strconv` package converts between text and numbers. Atoi gives an int and ParseFloat a float64, and both also return an error: with "12" it is nil, and with "twelve" it explains that the syntax is invalid. The other way round, Itoa turns an integer into text and FormatFloat(x, 'f', 2, 64) writes a decimal with two digits.

Code · main.go

package mainimport (	"fmt"	"strconv"	"strings")func main() {	line := "  milk, eggs ,bread,  olive oil  "	// Split cuts at each comma; TrimSpace removes the spaces around.	parts := strings.Split(line, ",")	for i := 0; i < len(parts); i++ {		parts[i] = strings.TrimSpace(parts[i])	}	fmt.Printf("%d items: %q\n", len(parts), parts)	fmt.Println(strings.Join(parts, " | "))	fmt.Println("Upper:", strings.ToUpper(parts[0]), "| has eggs:", strings.Contains(line, "eggs"))	fmt.Println("Replace:", strings.Replace(parts[3], "olive", "sunflower", 1), "| commas:", strings.Count(line, ","))	fmt.Println(strings.Repeat("-", 24))	// strconv turns text into numbers and numbers into text.	units, err := strconv.Atoi("12")	fmt.Println("12 units x 2 =", units*2, "error:", err)	price, _ := strconv.ParseFloat("2.75", 64)	fmt.Println("Price x 2 =", price*2)	if _, err := strconv.Atoi("twelve"); err != nil {		fmt.Println("Error:", err)	}	label := "Pack of " + strconv.Itoa(units) + ": " + strconv.FormatFloat(price*float64(units), 'f', 2, 64)	fmt.Println(label)}

Output · go run main.go

4 items: ["milk" "eggs" "bread" "olive oil"]
milk | eggs | bread | olive oil
Upper: MILK | has eggs: true
Replace: sunflower oil | commas: 3
------------------------
12 units x 2 = 24 error: <nil>
Price x 2 = 5.5
Error: strconv.Atoi: parsing "twelve": invalid syntax
Pack of 12: 33.00

Key points

  • strings.Split cuts and strings.Join joins.
  • TrimSpace, ToUpper and Replace return a new string.
  • Contains, HasPrefix and Count ask about the content.
  • strconv.Atoi and ParseFloat turn text into numbers, with an error.
  • strconv.Itoa and FormatFloat turn numbers into text.

Exercise

Split the text "name=Ana;age=34;city=Bilbao" with strings.Split on ; and each piece on =, print each key with its value, and convert the age with strconv.Atoi to add 1 to it.