Sobes.tech
Junior

How to determine the number of characters in a string in Go?

sobes.tech AI

Answer from AI

In Go, the number of characters (runes, code points) in a string is determined by the function utf8.RuneCountInString.

Example:

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	str := "Привет, World!"
	count := utf8.RuneCountInString(str)
	fmt.Println(count) // Output: 14
}

Using len(str) directly returns the number of bytes, not characters in UTF-8.

Example with len():

package main

import (
	"fmt"
)

func main() {
	str := "Привет" // 12 bytes in UTF-8
	byteCount := len(str)
	fmt.Println(byteCount) // Output: 12 (number of bytes)
}