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
- Start with "a=b"
- Do this Separate at =
- Result b
package main
import "fmt"
import "strings"
func main() {
_, value, found := strings.Cut("a=b", "=")
if found {
fmt.Println(value)
}
}
b
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.
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
package main
import (
"fmt"
"strings"
)
func main() {
key, value, found := strings.Cut(" city = Lima ", "=")
if found {
fmt.Println(strings.TrimSpace(key) + "=" + strings.TrimSpace(value))
}
}
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.