Golang : How to print rune, unicode, utf-8 and non-ASCII CJK(Chinese/Japanese/Korean) characters?
Problem :
You want to print rune, unicode or CJK(Chinese/Japanese/Korean) characters with Golang, but you are getting funny result. How to print rune properly?
Solution :
Use quoted verb in your Printf statement. From https://blog.golang.org/strings :
"The %q (quoted) verb will escape any non-printable byte sequences in a string so the output is unambiguous."
For example :
package main
import (
"fmt"
)
func main() {
sr := '\u212A'
fmt.Println(sr) // wrong way to print!
fmt.Printf("%+q\n", sr) // print back the unicode
fmt.Printf("%q\n", sr) // print K (Kelvin symbol)
src := '你'
fmt.Printf("%q\n", src) // print character 你
fmt.Printf("%+q\n", src) // print unicode codepoint
}
Output :
8490
'\u212a'
'K'
'你'
'\u4f60'
Reference :
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+12.1k Golang : Image to ASCII art example
+6k Golang : Null and nil value
+5k Golang : Extract unicode string from another unicode string example
+26.4k Golang : Move file to another directory
+6k Golang : How to detect if a sentence ends with a punctuation?
+6.3k Golang : Calculate how many weeks left to go in a given year
+10.8k Golang : Print UTF-8 fonts on image example
+27.8k Golang : Save map/struct to JSON or XML file
+5.2k Golang : Experimental emojis or emoticons icons programming language
+18.3k Golang : Count JSON objects and convert to slice/array
+4.8k Cash Flow : 50 days to pay your credit card debt
+29.3k Golang : How to convert(cast) string to IP address?