While using strings.Map(mapping func(rune) rune, s string) string
to manipulate a string, the mapping function can return -1 (or any negative values) to filter out unwanted runes. Here is the reference.
Some useful situations:
func filterAndLower(r rune) rune {
if !unicode.IsLetter(r) {
return -1
}
return unicode.ToLower(r)
}
[...]
input := "Hello 123 World"
hello := strings.Map(filterAndLower, in) // return value: "helloworld"
[...]
// It can also be combined with string.Builder when one is needed
sb := strings.Builder{}
sb.Grow(len(hello))
sb.WriteString(hello)
[...]
Top comments (0)