How to Count Occurrences of a Substring in Go

Use strings.Count or bytes.Count to find the number of non-overlapping substring occurrences in Go.

Use strings.Count to count non-overlapping occurrences of a substring in a string.

package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "hello world, hello universe"
	count := strings.Count(text, "hello")
	fmt.Println(count) // Output: 2
}

For byte slices, use bytes.Count instead:

package main

import (
	"fmt"
	"bytes"
)

func main() {
	text := []byte("hello world, hello universe")
	count := bytes.Count(text, []byte("hello"))
	fmt.Println(count) // Output: 2
}