Home
Go
strings.Count Examples
This page was last reviewed on Sep 13, 2024.
Dot Net Perls
Count. How many instances of a substring occur within a string? We can find non-overlapping instances with the strings.Count function in the Go language.
Though this computation would be possible with nested for-range loop, using strings.Count is clearer and easier to maintain. For special requirements, custom code would still needed.
Example. This Go program has some string literals and uses strings.Count on them. We can use strings.Count on any string, not just one specified as a literal.
String Literal
Part 1 The sentence stored in the "text" string contains the word "the" in 2 separate places, so this call to Count() returns 2.
Part 2 Count can be used with single-character strings, and this can be used to count specific letters.
Part 3 Suppose a substring occurs as part of another counted substring. With Count(), each match is excluded from further counting.
Part 4 With an empty string argument, we get a count of Unicode code points plus one. For ASCII values, this is equal to the length plus one.
package main import ( "fmt" "strings" ) func main() { text := "This has the word the 2 times." // Part 1: count the word "the." count := strings.Count(text, "the") fmt.Println("Count(the) =", count) // Part 2: has the lowercase letter "t" 3 times. count2 := strings.Count(text, "t") fmt.Println("Count(t) =", count2) // Part 3: two non-overlapping instances of the substring. text2 := "catcatcatcat" count3 := strings.Count(text2, "catcat") fmt.Println("Count(catcat) =", count3) // Part 4: with an empty argument, Count returns count of unicode code points. text3 := "bird" count4 := strings.Count(text3, "") fmt.Println("Count() =", count4, ", len =", len(text3)) }
Count(the) = 2 Count(t) = 3 Count(catcat) = 2 Count() = 5 , len = 4
Summary. In many Go programs, the built-in strings.Count method is sufficient. And in these places, Count() should be preferred as it is well-tested and will not complicate your code.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 13, 2024 (new).
Home
Changes
© 2007-2024 Sam Allen.