在实际运用有很多须要中文和unicode转换的场景,这里紧张先容通过golang实现中文和unicode相互转换。
1、中文转unicode这一步比较大略
示例

sText := "hello 你好" textQuoted := strconv.QuoteToASCII(sText) textUnquoted := textQuoted[1 : len(textQuoted)-1] fmt.Println(textUnquoted)
2、unicode 转中文
网上有些例子,通过 \u 分隔来实现,这种办法存在局限性。比如字符里面含有非中笔墨符,就会涌现问题。
精确转换示例
package mainimport ( "fmt" "strconv" "strings")func zhToUnicode(raw []byte) ([]byte, error) { str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(raw)), `\\u`, `\u`, -1)) if err != nil { return nil, err } return []byte(str), nil}func main() { sText := "hello 你好" textQuoted := strconv.QuoteToASCII(sText) textUnquoted := textQuoted[1 : len(textQuoted)-1] fmt.Println(textUnquoted) v, _ := zhToUnicode([]byte(textUnquoted)) fmt.Println(string(v))}
strconv.Quote(s string)string -> 返回字符串在go语法下的双引号字面值表示,掌握字符和不可打印字符会进行转义(\t,\n等)strconv.Unquote(s string)(t string,err error) -> 函数假设s是一个半引号、双引号、反引号包围的go语法字符串,解析它并返回它表示的值。(如果是单引号括起来的,函数会认为s是go字符字面值,返回一个单字符的字符串)links