Library contents

Go utf8.RuneCountInString

Count Unicode code points in valid text, including a supplementary symbol.

A simple example

utf8.RuneCountInString

  1. Start with "A😀"
  2. Do this Count Unicode code points
  3. Result 2
The letter and the emoji each contribute one code point.
main.go
package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    value := "A😀"
    fmt.Println(utf8.RuneCountInString(value))
}
Output
2

Syntax

Go syntax
utf8.RuneCountInString(value)
Run these examples in Go

Save one example at a time as main.go. Use Go 1.21 or later.

go run main.go

Count symbols in an attendance reaction

A student response can combine ordinary letters, accents and emoji. Choose the unit being counted before applying a length limit, because code points and visible symbols do not always line up.

From the programvalue := "A😀B"
Result3
main.go
package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    value := "A😀B"
    fmt.Println(utf8.RuneCountInString(value))
}
Output
3

The emoji counts once alongside two ASCII letters.

Advertisements

Count a decomposed accent

A student types an accented letter using a base letter followed by a combining mark. Count the Unicode code points and relate that result to the single accented letter visible on screen.

From the programvalue := "é"
Result2
main.go
package main

import (
    "fmt"
    "unicode/utf8"
)

func main() {
    value := "é"
    fmt.Println(utf8.RuneCountInString(value))
}
Output
2

The base e and combining mark are separate code points.

Read a parcel sorting code

The depot scans a parcel marked NC-17. This identifier uses only ASCII characters. Count all characters, including the separator, to check the scanner’s length field.

GivenNC-17
Worked result5

What to watch for

A displayed character may contain several code points. Validate the encoding of externally supplied bytes.

Documentation for utf8.RuneCountInString