DEV Community

Michele Caci
Michele Caci

Posted on

How to filter out runes using strings.Map() in Go

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)
[...]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)