参考文章: http://c.biancheng.net/view/36.html
1. 获取ascii类型字符的长度个数和获取utf8类型字符长度的个数
a. len("咪咪") //return 6 这获取的是ASCII长度
b.utf8.RuneCountInString("咪咪") // return 2获取的是utf8汉字长度个数
2. 字符串遍历,以ASCII方式遍历和以Unicode方式遍历
// 测试字符串长度
str := "我是 abcd"
// ASCII码类型遍历
for i := 0; i < len(str); i++ {
fmt.Printf("ASCII %c,%d\n",str[i],str[i])
}
// unicode码类型遍历
for _,s := range str {
fmt. Printf("Unicode %c,%d \n",s,s)
}
输出结果
@H_301_16@ASCII æ,230 ASCII ,136 ASCII ,1)">145 ASCII æ,1)"> ASCII ,1)">152 ASCII ¯,1)">175 ASCII,1)">32 ASCII a,1)">97 ASCII b,1)">98 ASCII c,1)">99 ASCII d,1)">100 Unicode 我,1)">25105 Unicode 是,1)">26159 Unicode,1)"> Unicode a,1)"> Unicode b,1)"> Unicode c,1)"> Unicode d,1)">100