Inaccurate string iteration
Mistake
This does not print ê
, but instead prints Ã
and the length is printed to be
6 instead of 5. This is because the character ê
requires 2 bytes to store.
s := "hêllo"
for i := range s {
fmt.Printf("position %d: %c\n", i, s[i])
}
fmt.Printf("len=%d\n", len(s))
Fix
Use range variables
s := "hêllo"
for i, r := range s {
fmt.Printf("position %d: %c\n", i, r)
}
Cast the string to a rune slice
s := "hêllo"
runes := []rune(s)
for i := range runes {
fmt.Printf("position %d: %c\n", i, runes[i])
}