Published Jun 12, 2023
Contribute to Docs

The Count() function returns the number of times a given substring appears in a given string without overlapping.


strings.Count(str, sub)

Where str is the string being searched. sub, on the other hand, is the substring being searched for. It returns an int as the number of non-overlapping occurrences of sub in str. When sub is an empty string, Count() will count the boundaries before and after each character in str. (i.e. When str is “A” and sub is “”, Count() returns 2. When str is “ABC” and sub is “”, then Count() returns 4.)


The following example searches for the letter “e” in “Codecademy” and prints out the result.

package main
import (
func main() {
name := "Codecademy"
find := "e"
fmt.Println(find, "is in", name, strings.Count(name,find), "times")

This results in the following output:

e is in Codecademy 2 times

Codebyte Example

The following example shows how Count() only counts non-overlapping substrings.

Visit us
Hide code
Hide output
Hide output

All contributors

Looking to contribute?

Learn Go on Codecademy