Count Rune Frequency Across Text

Tally each Unicode code point with a map keyed by rune, then report counts in sorted order so the histogram is deterministic.

GoData Integrity

Code

gosnippet
27 lines
package main

import (
	"fmt"
	"sort"
)

func main() {
	text := "gögogo"

	counts := make(map[rune]int)
	for _, r := range text {
		counts[r]++
	}

	runes := make([]rune, 0, len(counts))
	for r := range counts {
		runes = append(runes, r)
	}
	sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] })

	fmt.Println("byte length:", len(text))
	fmt.Println("rune count:", len([]rune(text)))
	for _, r := range runes {
		fmt.Printf("%q x%d\n", r, counts[r])
	}
}

What the code performs

The moving parts are the function main.

for _, r := range text is the loop that carries the per-item work.

Points of care

  • The platform already ships each API used, so no installation precedes the run.

Applying it

The entry-point signature is func main()

The run prints byte length:, rune count: — each prefix names the step that produced it.

Statements that matter

sort.Slice(runes, func(i, j int) bool { return runes[i] < runes[j] })
for _, r := range runes {
	fmt.Printf("%q x%d\n", r, counts[r])
}
for _, r := range text {
	counts[r]++
}

Interactive Tools for This Topic

FAQ

What does Count Rune Frequency Across Text print when run?
No setup needed: run the file and look for labeled lines like `byte length:`, `rune count:` in the output.