Lesson contents

Go — Parsing strings with Cut

Go strings.Cut splits at the first occurrence of a separator and reports whether it was found. TrimSpace removes surrounding whitespace from each field.

A simple example

Split one line of text

  1. Start with "a=b"
  2. Do this Separate at =
  3. Result b
The separator marks where the first field ends and the second begins. Read the second field.
main.go
package main

import "fmt"
import "strings"

func main() {
    _, value, found := strings.Cut("a=b", "=")
    if found {
        fmt.Println(value)
    }
}
Output
b
Advertisements

Split one setting into a key and a value

strings.Cut returns the text before and after the first separator and a boolean indicating whether it was present. TrimSpace removes surrounding Unicode whitespace while preserving spaces within a value.

Saved line: city = Lima. Setting name: city. Display value: Lima.
Read a destination from a settings file

A noticeboard reads its city from a saved setting. Split the line at its first equals sign and trim the spaces around the two fields. The board can now look up city and display Lima.

Run the example

Go 1.20 or later. Run these commands from the directory containing the example.

go run main.go
main.go
package main

import (
	"fmt"
	"strings"
)

func main() {
	key, value, found := strings.Cut(" city = Lima ", "=")
	if found {
		fmt.Println(strings.TrimSpace(key) + "=" + strings.TrimSpace(value))
	}
}
Output
city=Lima

The input contains padding around city and Lima. Locating the first separator identifies the two fields. Trimming their ends gives city=Lima without changing text inside the value.

Try it yourself

What should city = A=B produce?

Check your answer

The value retains its second equals sign. The normalized line is city=A=B. Decide separately whether an empty key is valid for your file format.

A Tour of Go

Related tags

  • Go
  • strings
  • parsing
  • whitespace