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 strings.
Return value
Count returns the count of non-overlapping instances of substr in s.
- If the input substring is empty,
Countreturns 1 + the number of Unicode code points in strings, 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.
Code
In the code below, we first import the fmt and strings packages to our program.
package mainimport ("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 returns2because 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 returns2because 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 returns7as 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 thefmtpackage.
Output
The program prints the output below and exits.
educative e 2
appleisappleisappl apple 2
google 7