Count Substring Occurrences With strings.Count
Measure how many times a substring appears with strings.Count, including the overlapping-free rule that distinguishes it from a manual scan.
Code
package main
import (
"fmt"
"strings"
)
func main() {
log := "retry retry retry success retry"
// 非重叠计数:"aaa" 在 "aaaa" 里只算 1 次
fmt.Println("overlaps not counted:", strings.Count("aaaa", "aa"))
fmt.Println("retry hits:", strings.Count(log, "retry"))
// 空串匹配在任何字符边界之间,所以比 len 多 1
fmt.Println("empty string matches:", strings.Count("hello", ""))
// 统计分隔符数量可以推断字段数
csv := "id,name,email"
fmt.Printf("%d fields implied by %d commas\n",
strings.Count(csv, ",")+1, strings.Count(csv, ","))
}Inside the snippet
Count Substring Occurrences With strings.Count keeps everything in the function main.
What to watch for
- Nothing third-party is pulled in; the snippet is dependency-free.
Putting it to use
Entry signature: func main()
The file’s steps show up in the output as overlaps not counted:, retry hits:, empty string matches:.
Core lines
log := "retry retry retry success retry"
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Count Substring Occurrences With strings.Count print when run?
- Running the file directly is enough — expect labeled output lines such as `overlaps not counted:`, `retry hits:`, `empty string matches:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.