Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

What is the Count function in Golang?

Faraz Karim

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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 the string type and represents the text you want to search in.

  • substr: This argument is also of the string type and represents the part of the text that you want to search.

Return value

The Count function returns the number of instancesexcluding overlapping instances of a substring present in the given 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 main
import (
"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 main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.Count("Beep Beep I'm a Sheep", ""))
}

RELATED TAGS

golang
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring