Junior — Middle
How to determine the size in bytes occupied by a single character in a string?
sobes.tech AI
Answer from AI
In Go, a string (string) represents a sequence of bytes in UTF-8 encoding. To determine how many bytes a single character (rune) occupies, you need to consider that different characters can take up different amounts of bytes.
If you want to find out the size of a specific character in bytes, you can convert the string into a slice of runes ([]rune) and compare the length of the original string with the length of the rune slice.
Example:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
s := "Привет"
for i, w := 0, 0; i < len(s); i += w {
r, width := utf8.DecodeRuneInString(s[i:])
fmt.Printf("Character: %c occupies %d bytes\n", r, width)
w = width
}
}
Here, utf8.DecodeRuneInString returns a rune and the number of bytes it occupies. Thus, you can determine the size of each character in bytes.