How to count a substring's occurrence in a string in Go

The string package is a Go standard library package that contains functions to manipulate UTF-8 encoded strings.

The Count() method

The string package provides the Count() method, which can be used to count the number of times a non-overlapping instance of a substring appears in a string in Go.

Syntax

func Count(s, substr string) int

Parameters

This function takes two arguments:

  • string s: This is the first argument.
  • substring substr: This is the argument that will be searched for in string s.

Return value

Count returns the count of non-overlapping instances of substr in s.

  • If the input substring is empty, Count returns 1 + the number of Unicode code points in string s, as there is an empty string before and after each code point in a string.

A Unicode code point is an integer value that uniquely identifies a given character. There are different encodings, like UTF-8 or UTF-16, that we can use to encode the Unicode characters. Each character’s Unicode code point can be encoded as one or more bytes, specified by the encodings.

Getting the count of substring in a string using the Count() method

Code

In the code below, we first import the fmt and strings packages to our program.

package main
import (
"fmt"
"strings"
)
func main() {
str1 := "educative"
str2 := "appleisappleisappl"
str3 := "google"
fmt.Println(str1 , "e", strings.Count(str1, "e"))
fmt.Println(str2, "apple", strings.Count(str2, "apple"))
fmt.Println(str3, "", strings.Count(str3, ""))
}

Explanation

  • After importing, we call the Count() method with "educative" as the input string and "e" as the substring. This returns 2 because the substring "e" appears twice in the string "educative".

  • We again call the Count() method with "appleisappleisappl" as the input string and "apple" as the substring. This also returns 2 because the substring "apple" only appears twice in the string "appleisappleisappl".

  • We test the Count() method with "google" as the string and an empty substring. It returns 7 as the output, which is 1 + the number of Unicode code points in the "google" string.

  • To show the output of all these operations, we use the Println() method of the fmt package.

Output

The program prints the output below and exits.

educative e 2
appleisappleisappl apple 2
google  7

Free Resources