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 = #str10 local charCount = 011 local i = 112 while (i <= lenInByte) 13 do14 local curByte = string.byte(str, i)15 local byteCount = 1;16 if curByte > 0 and curByte <= 127 then17 byteCount = 1 --1字节字符18 elseif curByte >= 192 and curByte < 223 then19 byteCount = 2 --双字节字符20 elseif curByte >= 224 and curByte < 239 then21 byteCount = 3 --汉字22 elseif curByte >= 240 and curByte <= 247 then23 byteCount = 4 --4字节字符24 end25 26 local char = string.sub(str, i, i + byteCount - 1)27 i = i + byteCount -- 重置下一字节的索引28 charCount = charCount + 1 -- 字符的个数(长度)29 end30 return charCount31 end