Skip to content
Tutorials Center
My learning

Topics

Go Reference · bytes, unicode and text

Go utf8.RuneCountInString() function

Reference for Go utf8.RuneCountInString and RuneCount: count the runes in a string or byte slice, how invalid UTF-8 is counted, and how it differs from len().

utf8.RuneCountInString(s) returns the number of runes (Unicode code points) in the string s. It lives in the package unicode/utf8. The built-in len(s) counts bytes, and for any text outside plain ASCII the two numbers differ.

utf8.RuneCount(p) does the same for a []byte, and utf8.RuneCountInString is what you want when you have a string. Neither function allocates.

Go
n := utf8.RuneCountInString("héllo") // 5, while len("héllo") is 6

Try it

Go Bytes versus runes

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Invalid bytes and combining marks

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func RuneCountInString(s string) (n int)
func RuneCount(p []byte) int
func RuneLen(r rune) int
Name Description
s The string to measure.
p The byte slice to measure (RuneCount).

Returns: the number of runes. An empty string gives 0.

Edge cases: the functions never fail and never panic. Every byte that is not part of a valid UTF-8 sequence counts as one rune (decoded as utf8.RuneError, U+FFFD with width 1).

Usage notes

  • Cost is linear. The function scans the whole string, so call it once and keep the result instead of calling it in a loop condition. len(s) is constant time.
  • Same as len([]rune(s)) but without allocating the rune slice. Prefer RuneCountInString when you only need the count.
  • A rune is not a user-perceived character. A letter plus a combining accent, many emoji with skin-tone modifiers and flags are several runes. Grapheme-cluster counting needs a third-party text package.
  • Padding and column widths: fmt width flags such as %-8s pad by rune count, not by display width, so East Asian wide characters still look misaligned in a terminal.
  • Check validity separately with utf8.ValidString if you need to reject malformed input, since the count alone hides invalid bytes.
  • for range over a string also decodes runes, so counting with a loop gives the same result, just slower.
  • Truncating text: convert a rune count to a byte offset with utf8.DecodeRuneInString (see the second example) so you never slice through a multi-byte sequence.