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.
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
contains the word "the" in 2 separate places, so this call to Count()
returns 2.Count
can be used with single-character strings, and this can be used to count specific letters.Count()
, each match is excluded from further counting.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
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.