Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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

like image 992
hardPass Avatar asked May 22 '13 03:05

hardPass


People also ask

What is rune in Go lang?

A rune is an alias to the int32 data type. It represents a Unicode code point. A Unicode code point or code position is a numerical value that is usually used to represent a Unicode character.

Is Unicode the same as string?

Unicode is a standard encoding system that is used to represent characters from almost all languages. Every Unicode character is encoded using a unique integer code point between 0 and 0x10FFFF . A Unicode string is a sequence of zero or more code points.

What is rune slice?

When you convert a string to a rune slice, you get a new slice that contains the Unicode code points (runes) of the string. For an invalid UTF-8 sequence, the rune value will be 0xFFFD for each invalid byte.

What is the Unicode method?

Unicode is a digital standard for the consistent encoding of the world's writing systems, so that representation of character sets is consistent around the world. The first 256 Unicode characters (0, 255) correspond to the ASCII character set.


1 Answers

package main

import "fmt"
import "strconv"

func main() {
    quoted := strconv.QuoteRuneToASCII('啊') // quoted = "'\u554a'"
    unquoted := quoted[1:len(quoted)-1]      // unquoted = "\u554a"
    fmt.Println(unquoted)
}

This outputs:

\u554a
like image 179
Darshan Rivka Whittle Avatar answered Oct 21 '22 19:10

Darshan Rivka Whittle