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.

GoData Integrity

Code

gosnippet
22 lines
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

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:`.