How to count the occurences of a character in a Go string
The simplest way to count the number of occurrences of a character in a string
in Go is by using the strings.Count
method. For example, to count how many times a
appears in ‘Mary had a little
lamb’, use the following code snippet:
package main
import (
"fmt"
"strings"
)
func main() {
str := "Mary had a little lamb"
fmt.Println(strings.Count(str, "a")) // 4
}
Run this example on the Go playground
Thanks for reading, and happy coding!