The Count() Function in the Golang strings package is used to count the number of instances of a specified substring in the given string. It returns an integer value.
Count() Syntax
The Count() function syntax:
func Count(s1, substr string) int
Count() Parameters:
The Count() function takes two parameters
- s1 is the string
- substr is the string
Count() Return Value:
The strings package Count() function returns an int value. If the substring is an empty string, the Count function will return 1+ length of a given string.
Let’s understand the string package Count() method with examples.
How to Count Substrings in Golang Using Count()
The following go program gets the count of the substring that appears in the given string using the strings.Count() function.
package main import ( "fmt" "strings" ) func main() { // Check if a string contains a specified Unicode code point rune fmt.Println(strings.Count("I love Go Programming!", "g")) fmt.Println(strings.Count("Count the characters", "the")) fmt.Println(strings.Count("Length", "")) }
The output of the substring count in go are:
2
1
7
In the above program,
The first output returns 2 as the substring “g” appears twice in the given string “I love Go Programming!”
The second output returns 1 as the substring “the” appears only once in the given string “Count the characters”
The third output returns 7 as the substring is an empty string, hence it returns 1+ length of a given string “Length”.
Cool Tip: How to use the string ContainsRune function in Golang!
Conclusion
I hope the above article on counting Unicode code points of the substring in the given string using the Count() method is helpful to you.
You can find more topics about the Golang tutorials on the GolangSpot Home page.