lua获取字符长度

对中英文不同字节进行:

function getStringCharCount(str)

    local lenInByte = #str

    local charCount = 0   

    local i = 1

    while (i <= lenInByte)

    do

        local curByte = string.byte(str, i)

        local byteCount = 1;

        if curByte > 0 and curByte <= 127 then

            byteCount = 1                                              --1字节字符

        elseif curByte >= 192 and curByte < 223 then

            byteCount = 2                                              --双字节字符

        elseif curByte >= 224 and curByte < 239 then

            byteCount = 3                                              --中文

        elseif curByte >= 240 and curByte <= 247 then

            byteCount = 4                                              --4字节字符

        end


        local char = string.sub(str, i, i + byteCount - 1)

        i = i + byteCount                                              -- 重置下一字节的索引

        charCount = charCount + 1                                      -- 字符的个数(长度)

    end

    return charCount

end

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容