Junior — Middle
How to determine the number of characters in a string value?
sobes.tech AI
Answer from AI
In Go, to determine the number of characters in a string, you need to consider that a string is a sequence of bytes, and characters (runes) can occupy multiple bytes (UTF-8).
To get the number of characters (runes), use the utf8.RuneCountInString function from the unicode/utf8 package:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "Привет"
count := utf8.RuneCountInString(s)
fmt.Println(count) // Will output 6
}
If you use just len(s), it will return the number of bytes, not characters.