lua获取字符长度

2019-05-23  本文已影响0人  Wintersnowcream

对中英文不同字节进行:

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

上一篇 下一篇

猜你喜欢

热点阅读