1 --[[ 2 @desc: 计算字符串字符个数 3 author:{author} 4 time:2017-12-29 16:08:11 5 --@inputstr: 源字符串 6 return 字符个数 7 ]] 8 function getStringCharCount(str) 9 local lenInByte = #str 10 local charCount = 0 11 local i = 1 12 while (i <= lenInByte) 13 do 14 local curByte = string.byte(str, i) 15 local byteCount = 1; 16 if curByte > 0 and curByte <= 127 then 17 byteCount = 1 --1字节字符 18 elseif curByte >= 192 and curByte < 223 then 19 byteCount = 2 --双字节字符 20 elseif curByte >= 224 and curByte < 239 then 21 byteCount = 3 --汉字 22 elseif curByte >= 240 and curByte <= 247 then 23 byteCount = 4 --4字节字符 24 end 25 26 local char = string.sub(str, i, i + byteCount - 1) 27 i = i + byteCount -- 重置下一字节的索引 28 charCount = charCount + 1 -- 字符的个数(长度) 29 end 30 return charCount 31 end