Home >Backend Development >Golang >How to Convert Unicode Code Points to Characters in Go?
Converting Unicode Code Points to Characters in Go
When working with text files, you may encounter situations where characters are encoded as Unicode code points. To display these characters in their literal form, you'll need to convert the code points to characters.
In this specific example, you have a text file containing Unicode code points:
\u0053 \u0075 \u006E
You want to convert these code points to their corresponding characters:
S u n
To achieve this conversion, you can utilize the strconv.Unquote() and strconv.UnquoteChar() functions.
Using strconv.Unquote()
If your strings are enclosed in quotes, you can use strconv.Unquote(). However, it requires you to add the quotes to the code points yourself:
lines := []string{ `\u0053`, `\u0075`, `\u006E`, } for i, v := range lines { var err error lines[i], err = strconv.Unquote(`"` + v + `"`) if err != nil { fmt.Println(err) } }
Using strconv.UnquoteChar()
If your strings represent a single rune, strconv.UnquoteChar() is more suitable. It doesn't require any quoting:
runes := []string{ `\u0053`, `\u0075`, `\u006E`, } for _, v := range runes { var err error value, _, _, err := strconv.UnquoteChar(v, 0) if err != nil { fmt.Println(err) } fmt.Printf("%c\n", value) }
After converting the code points, you'll have the following output:
S u n
The above is the detailed content of How to Convert Unicode Code Points to Characters in Go?. For more information, please follow other related articles on the PHP Chinese website!