To convert a string to a rune slice (UTF-32) using the strconv package in Golang, you can follow these steps:
import (
"strconv"
"unicode/utf8"
)
str := "Hello, 世界"
strLen := len(str)
runes := make([]rune, 0, utf8.RuneCountInString(str))
for i := 0; i < strLen; {
r, size := utf8.DecodeRuneInString(str[i:])
// Add the decoded rune to the rune slice
runes = append(runes, r)
// Move to the next byte
i += size
}
runes
will contain the UTF-32 representation of the string. You can print it for verification:fmt.Println(runes)
The complete code:
package main
import (
"fmt"
"strconv"
"unicode/utf8"
)
func main() {
str := "Hello, 世界"
strLen := len(str)
runes := make([]rune, 0, utf8.RuneCountInString(str))
for i := 0; i < strLen; {
r, size := utf8.DecodeRuneInString(str[i:])
runes = append(runes, r)
i += size
}
fmt.Println(runes)
}
This code will convert the string "Hello, 世界" to a rune slice [72 101 108 108 111 44 32 19990 30028]
.