len()
len返回int类型,表示字符的ascII字节长度。go的字符串使用utf-8格式保存,其中一个英文字符占1个字节,一个空格占1个字节,一个特殊字符占1个字节,一个中文字符占3个字节。len()还可以获取切片、通道的长度。
tip1 := "hello world!"
fmt.Println(len(tip1))
tip2 := "忍者"
fmt.Println(len(tip2))
// 12
// 6
utf8.RuneCountInstring()
如果希望按照认知习惯,用汉英字符的个数计数,使用utf8包的RuneCountInstring函数,统计unicode字符数量
fmt.Println(utf8.RuneCountInstring("忍者"))
fmt.Println(utf8.RuneCountInstring("龙忍出鞘,fight!"))
// 2
// 12
一般在用户注册或登陆账户时,要做字符长度限制,因此要使用unicode字符串长度