pu369com

golang实现unicode码和中文之间的转换

package main

import (
    "fmt"
    "strconv"
    "strings"
)

func main() {
    sText := "中文"
    textQuoted := strconv.QuoteToASCII(sText)
    textUnquoted := textQuoted[1 : len(textQuoted)-1]
    fmt.Println(textUnquoted)

    textUnquoted = `\u5de5\u5546\u94f6\u884c` //这里要用反引号

    sUnicodev := strings.Split(textUnquoted, "\\u")
    var context string
    for _, v := range sUnicodev {
        if len(v) < 1 {
            continue
        }
        temp, err := strconv.ParseInt(v, 16, 32)
        if err != nil {
            panic(err)
        }
        context += fmt.Sprintf("%c", temp)
    }
    fmt.Println(context)
}

 补充:写段代码输出6万来个unicode码看看

package main

import (
    "bytes"
    "fmt"
    "strconv"
    "strings"
)

var buffer bytes.Buffer

func main() {
    start := "0"
    result, _ := strconv.ParseInt(start, 16, 0)
    do(result)
    fmt.Println(buffer.String())
}
func do(result int64) {
    resultnext := result + 1
    textUnquoted := fmt.Sprintf("\\u%04x", resultnext)

    sUnicodev := strings.Split(textUnquoted, "\\u")
    var context string
    for _, v := range sUnicodev {
        if len(v) < 1 {
            continue
        }
        temp, err := strconv.ParseInt(v, 16, 32)
        if err != nil {
            panic(err)
        }
        context += fmt.Sprintf("%c", temp)
    }
    ss := fmt.Sprintf(" %x-%s ", resultnext, context)
    buffer.WriteString(ss)
    if resultnext > 65536 {
        return
    }
    do(resultnext)
}

 

 

 

 

 

参考:https://www.cnblogs.com/borey/p/5622812.html

https://blog.csdn.net/hherima/article/details/9045861

https://ask.csdn.net/questions/1021692

posted on 2020-06-04 15:54  pu369com  阅读(1252)  评论(0编辑  收藏  举报

导航