0
0
GoHow-ToBeginner · 3 min read

How to Count Occurrences in a String in Go

In Go, you can count occurrences of a substring in a string using strings.Count. This function returns how many non-overlapping instances of the substring appear in the main string.
📐

Syntax

The function strings.Count takes two arguments: the main string and the substring you want to count. It returns an int representing how many times the substring appears.

  • strings.Count(s, substr)
  • s: the string to search in
  • substr: the substring to count
go
package main

import (
	"fmt"
	"strings"
)

func main() {
	count := strings.Count("hello world", "l")
	fmt.Println(count) // Output: 3
}
Output
3
💻

Example

This example shows how to count the number of times the substring "go" appears in a string. It prints the count to the console.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "go is a great language. golang is often called go."
	count := strings.Count(text, "go")
	fmt.Println("Occurrences of 'go':", count)
}
Output
Occurrences of 'go': 4
⚠️

Common Pitfalls

One common mistake is expecting strings.Count to count overlapping substrings. It only counts non-overlapping occurrences. For example, counting "aa" in "aaa" returns 1, not 2.

Also, counting an empty substring returns 1 plus the length of the string, which can be confusing.

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	text := "aaa"
	count := strings.Count(text, "aa")
	fmt.Println("Count of 'aa' in 'aaa':", count) // Output: 1

	emptyCount := strings.Count(text, "")
	fmt.Println("Count of empty string in 'aaa':", emptyCount) // Output: 4
}
Output
Count of 'aa' in 'aaa': 1 Count of empty string in 'aaa': 4
📊

Quick Reference

Remember these points when using strings.Count:

  • Counts non-overlapping occurrences only.
  • Empty substring counts as length of string + 1.
  • Returns an integer count.

Key Takeaways

Use strings.Count to count non-overlapping occurrences of a substring in a string.
strings.Count does not count overlapping substrings.
Counting an empty substring returns the string length plus one.
The function returns an integer representing the count.
Always import the strings package to use strings.Count.