How to convert a rune to unicode-style-string like `\u554a` in Golang?

后端 未结 8 1772
心在旅途
心在旅途 2021-02-05 07:47

If you run fmt.Println(\"\\u554a\"), it shows \'啊\'.

But how to get unicode-style-string \\u554a from a rune \'啊\' ?

相关标签:
8条回答
  • 2021-02-05 08:33

    IMHO, it should be better:

    func RuneToAscii(r rune) string {
        if r < 128 {
            return string(r)
        } else {
            return "\\u" + strconv.FormatInt(int64(r), 16)
        }
    }
    
    0 讨论(0)
  • 2021-02-05 08:34
    fmt.Printf("\\u%X", '啊')
    

    http://play.golang.org/p/Jh9ns8Qh15

    (Upper or lowercase 'x' will control the case of the hex characters)

    As hinted at by package fmt's documentation:

    %U Unicode format: U+1234; same as "U+%04X"

    0 讨论(0)
提交回复
热议问题