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

后端 未结 8 1753
心在旅途
心在旅途 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:27

    I'd like to add to the answer that hardPass has.

    In the case where the hex representation of the unicode is less that 4 characters (ü for example) strconv.FormatInt will result in \ufc which will result in a unicode syntax error in Go. As opposed to the full \u00fc that Go understands.

    Padding the hex with zeros using fmt.Sprintf with hex formatting will fix this:

    func RuneToAscii(r rune) string {
        if r < 128 {
            return string(r)
        } else {
            return fmt.Sprintf("\\u%04x", r)
        }
    }
    

    https://play.golang.org/p/80w29oeBec1

提交回复
热议问题