Strings and Runes
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
const s = "สวัสดี"
// Print the length of the string in bytes
fmt.Println("Len:", len(s))
// Iterate over each byte and print its hexadecimal representation
for i := 0; i < len(s); i++ {
fmt.Printf("%x ", s[i])
}
fmt.Println()
// Print the count of runes in the string
fmt.Println("Rune count:", utf8.RuneCountInString(s))
// Iterate over each rune and print its Unicode code point and starting index
for idx, runeValue := range s {
fmt.Printf("%#U starts at %d\n", runeValue, idx)
}
fmt.Println("\nUsing DecodeRuneInString")
// Iterate over each rune using DecodeRuneInString and print its Unicode code point and starting index
for i, w := 0, 0; i < len(s); i += w {
runeValue, width := utf8.DecodeRuneInString(s[i:])
fmt.Printf("%#U starts at %d\n", runeValue, i)
w = width
// Examine the rune using the examineRune function
examineRune(runeValue)
}
}
// examineRune examines specific runes and prints custom messages
func examineRune(r rune) {
if r == 't' {
fmt.Println("found tee")
} else if r == 'ส' {
fmt.Println("found so sua")
}
}Output
Last updated