美文网首页
lua获取字符长度

lua获取字符长度

作者: Wintersnowcream | 来源:发表于2019-05-23 09:46 被阅读0次

对中英文不同字节进行:

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

相关文章

网友评论

      本文标题:lua获取字符长度

      本文链接:https://www.haomeiwen.com/subject/uefyoftx.html