strings TrimFunc Trims By Predicate

strings.TrimFunc strips leading and trailing runes while a predicate holds, with TrimLeftFunc and TrimRightFunc for one-sided variants.

GoData Integrity

Code

gosnippet
21 lines
package main

import (
	"fmt"
	"strings"
	"unicode"
)

func main() {
	raw := "-- 42 points --"

	// TrimFunc trims runes from both ends while the predicate holds
	trimmed := strings.TrimFunc(raw, func(r rune) bool {
		return !unicode.IsDigit(r) && !unicode.IsLetter(r)
	})
	fmt.Println(trimmed)

	// asymmetric variants trim only one side
	fmt.Println(strings.TrimLeftFunc("....5", func(r rune) bool { return r == '.' }))
	fmt.Println(strings.TrimRightFunc("5....", func(r rune) bool { return r == '.' }))
}

How the snippet works

Under the hood: the function main.

Points of care

  • Built-in APIs only, so there is no supply chain to vet.

Using it

The primary signature is func main()

Key statements

return !unicode.IsDigit(r) && !unicode.IsLetter(r)

Interactive Tools for This Topic

FAQ

How do you run strings TrimFunc Trims By Predicate?
It runs as-is — treat the file as the whole program and execute it.