Sobes.tech
Principal

What are the options for counting the number of characters in a string in Go? (discussion after the interview)

sobes.tech AI

Answer from AI

In Go, counting the number of characters in a string depends on what you consider a character — a byte, a rune (Unicode code point), or a grapheme (user-perceived character).

  1. Counting bytes:
s := "Привет"
count := len(s) // number of bytes
  1. Counting runes (Unicode code points):
import "unicode/utf8"

s := "Привет"
count := utf8.RuneCountInString(s) // number of runes
  1. Counting graphemes (grapheme clusters):

For accurate counting of user-perceived characters (e.g., considering complex emojis or combined characters), you should use third-party libraries like github.com/rivo/uniseg:

import "github.com/rivo/uniseg"

s := "👩‍👩‍👧‍👦"
graphemes := uniseg.NewGraphemes(s)
count := 0
for graphemes.Next() {
    count++
}

Thus, the method you choose depends on your task: for simple cases, utf8.RuneCountInString suffices; for precise counting of user-perceived characters, use graphemes.