Principal
How to count the number of characters (runes) in a string in Go?
sobes.tech AI
Answer from AI
In Go, to count the number of characters (runes) in a string, it is important to remember that a string is a sequence of bytes in UTF-8, and runes are Unicode code points. The number of bytes and the number of runes can differ.
To count the number of runes, you can use the utf8.RuneCountInString function from the unicode/utf8 package:
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "Привет, мир!"
count := utf8.RuneCountInString(s)
fmt.Println("Number of runes:", count)
}
This method correctly counts the number of characters, including multi-byte runes.