Skip to content

Instantly share code, notes, and snippets.

@xlqstar
Created September 1, 2013 12:29
Show Gist options
  • Save xlqstar/6404175 to your computer and use it in GitHub Desktop.
Save xlqstar/6404175 to your computer and use it in GitHub Desktop.
//编码过程中避免不了中文字符,那我们该如何提取一个中文呢?首先我们要知道string[index]获取的是字符byte,就无法像C#中"老虞"[0]来取到‘老’,在Go中需要将字符串转换成rune数组,runne数组中就可以通过数组下标获取一个汉字所标识的Unicode码,再将Unicode码按创建成字符串即可。
//查看示例代码
str :="laoYu老虞"
for i:=0;i<len(str);i++ {
fmt.Println(str[i])
}
for i,s := range str {
fmt.Println(i,"Unicode(",s,") string=",string(s))
}
r := []rune(str)
fmt.Println("rune=",r)
for i:=0;i<len(r) ; i++ {
fmt.Println("r[",i,"]=",r[i],"string=",string(r[i]))
}
/*
Outut:
108
97
111
89
117
232
128
129
232
153
158
0 Unicode( 108 ) string= l
1 Unicode( 97 ) string= a
2 Unicode( 111 ) string= o
3 Unicode( 89 ) string= Y
4 Unicode( 117 ) string= u
5 Unicode( 32769 ) string= 老
8 Unicode( 34398 ) string= 虞
rune= [108 97 111 89 117 32769 34398]
r[ 0 ]= 108 string= l
r[ 1 ]= 97 string= a
r[ 2 ]= 111 string= o
r[ 3 ]= 89 string= Y
r[ 4 ]= 117 string= u
r[ 5 ]= 32769 string= 老
r[ 6 ]= 34398 string= 虞
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment