What is the Count function in Golang?
The Count function counts the number of times a substring appears inside a string.
To use this function, you must import the strings package in your file and access the Count function within it using the . notation (string.Count). Here, Count is the actual function, while string is the Go package that stores the definition of this function.
Function definiton
The definition of the Count function inside the string package is shown below.
Parameters
The Count function takes two arguments:
-
str: This argument is of thestringtype and represents the text you want to search in. -
substr: This argument is also of thestringtype and represents the part of the text that you want to search.
Return value
The Count function returns the number of string.
However, if the substring is empty, the Count function returns one more than the number of Unicode code characters used in the given string.
Code
Below is a simple example where we find the number of overlapping instances of ee in the given phrase.
package mainimport ("fmt""strings")func main() {fmt.Println(strings.Count("Beep Beep I'm a Sheep", "ee"))}
The following code example shows that the Count function outputs the length of the string plus 1 when you give an empty substring as an argument.
package mainimport ("fmt""strings")func main() {fmt.Println(strings.Count("Beep Beep I'm a Sheep", ""))}