Go by Example - Strings and Runes
Go by Example - Strings and Runes
com/strings-and-runes
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
Indexing into a string produces the raw byte for i := 0; i < len(s); i++ {
values at each index. This loop generates the hex fmt.Printf("%x ", s[i])
values of all the bytes that constitute the code }
fmt.Println()
points in s.
To count how many runes are in a string, we can fmt.Println("Rune count:", utf8.RuneCountInString(s))
use the utf8 package. Note that the run-time of
RuneCountInString depends on the size of the
string, because it has to decode each UTF-8 rune
sequentially. Some Thai characters are
represented by UTF-8 code points that can span
multiple bytes, so the result of this count may be
surprising.
A range loop handles strings specially and decodes for idx, runeValue := range s {
each rune along with its offset in the string. fmt.Printf("%#U starts at %d\n", runeValue, idx)
}
$ go run strings-and-runes.go
Len: 18
e0 b8 aa e0 b8 a7 e0 b8 b1 e0 b8 aa e0 b8 94 e0 b8 b5
Rune count: 6
1 of 2 11/26/24, 23:34
Go by Example: Strings and Runes https://gobyexample.com/strings-and-runes
Using DecodeRuneInString
U+0E2A 'ส' starts at 0
found so sua
U+0E27 'ว' starts at 3
U+0E31 'ั' starts at 6
U+0E2A 'ส' starts at 9
found so sua
U+0E14 'ด' starts at 12
U+0E35 'ี' starts at 15
2 of 2 11/26/24, 23:34