Go Count()
Published Jun 12, 2023
Contribute to Docs
The Count() function returns the number of times a given substring appears in a given string without overlapping.
Syntax
strings.Count(str, sub)
Where str is the string being searched. sub, on the other hand, is the substring being searched for. It returns an int as the number of non-overlapping occurrences of sub in str. When sub is an empty string, Count() will count the boundaries before and after each character in str. (i.e. When str is “A” and sub is “”, Count() returns 2. When str is “ABC” and sub is “”, then Count() returns 4.)
Example
The following example searches for the letter “e” in “Codecademy” and prints out the result.
package mainimport ("fmt""strings")func main() {name := "Codecademy"find := "e"fmt.Println(find, "is in", name, strings.Count(name,find), "times")}
This results in the following output:
e is in Codecademy 2 times
Codebyte Example
The following example shows how Count() only counts non-overlapping substrings.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Go on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn how to use Go (Golang), an open-source programming language supported by Google!
- Beginner Friendly.6 hours