Go – Count Substring in String

To count or get the number of occurrences of a substring in a string in Go language, call Count function of strings package, and pass the string and substring as arguments to it.

The syntax to count the occurrences of substring substr in string str using Count function is

strings.Count(str, substr)

Count function returns an integer representing the number of non-overlapping occurrences of substring in the string.

Examples

In the following example, we take two strings, str and substr, and count the occurrences of substr in str using Count function.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "Good Morning! Good Day!"
	substr := "Good"
	count := strings.Count(str, substr)
	fmt.Println("The number of occurrences of substring in the string is: ", count)
}

Output

The number of occurrences of substring in the string is:  2

Now, let us take the values for str and substr, such there substr has overlapping occurrences in str. We know that count only returns non-overlapping occurrences.

example.go

package main

import (
	"fmt"
	"strings"
)

func main() {
	str := "ababababa"
	substr := "aba"
	count := strings.Count(str, substr)
	fmt.Println("The number of occurrences of substring in the string is: ", count)
}

There are 4 overlapping occurrences of aba in ababababa, but only 2 non-overlapping occurrences.

Output

The number of occurrences of substring in the string is:  2

Conclusion

In this Golang Tutorial, we learned how to count the number of non-overlapping occurrences of a substring in a string in Go programming language, with the help of example programs.