/
unicode_test.go
73 lines (67 loc) · 1.36 KB
/
unicode_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"fmt"
"strconv"
"strings"
"testing"
"unicode"
)
func StrToUnicode(str string) string {
DD := []rune(str)
finallStr := ""
for i := 0; i < len(DD); i++ {
if unicode.Is(unicode.Scripts["Han"], DD[i]) {
textQuoted := strconv.QuoteToASCII(string(DD[i]))
finallStr += textQuoted[1 : len(textQuoted)-1]
} else {
h := fmt.Sprintf("%x", DD[i])
finallStr += "\\u" + isFullFour(h)
}
}
return finallStr
}
func isFullFour(str string) string {
if len(str) == 1 {
str = "000" + str
} else if len(str) == 2 {
str = "00" + str
} else if len(str) == 3 {
str = "0" + str
}
return str
}
////////// string to unicode
func TestStr2Unicode(t *testing.T) {
s := StrToUnicode(">")
fmt.Println(s)
}
func unicode2utf8(source string) string {
var res = []string{""}
sUnicode := strings.Split(source, "\\u")
var context = ""
for _, v := range sUnicode {
var additional = ""
if len(v) < 1 {
continue
}
if len(v) > 4 {
rs := []rune(v)
v = string(rs[:4])
additional = string(rs[4:])
}
temp, err := strconv.ParseInt(v, 16, 32)
if err != nil {
context += v
}
context += fmt.Sprintf("%c", temp)
context += additional
}
res = append(res, context)
return strings.Join(res, "")
}
////////// unicode to utf8
func TestUnicode2utf8(t *testing.T) {
unicodeStr := "\u003c" // >
s := unicode2utf8(unicodeStr)
fmt.Println(s)
}