💻 Tech
To safely and correctly decode a UTF-8 string via a loop, you can do it in two ways:
- Using
for..rangeloop
s := "Hello"
for _, r := range s {
fmt.Printf("%c", r)
}
// Output: Hello
For..range already handles UTF-8 values with runes that have a variable length.
- Using
utf8.DecodeRuneInStringfunction
s := "Hello"
for i := 0; i < len(s); i++ {
r, size := utf8.DecodeRuneInString(s)
if size > 1 {
i += size - 1 // Skip the rest of the bytes of the character since it's already read
}
fmt.Printf("%c", r)
}
// Output: Hello