Lua实现计算 UTF8 字符串的长度,每一个中文算一个字符

-- 计算 UTF8 字符串的长度,每一个中文算一个字符
-- @function [parent=#string] utf8len
-- @param string input 输入字符串
-- @return integer#integer  长度

计算 UTF8 字符串的长度,每一个中文算一个字符

local input = "你好World"
print(string.utf8len(input))
-- 输出 7



function string.utf8len(input)
    local len  = string.len(input)
    local left = len
    local cnt  = 0
    local arr  = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
    while left ~= 0 do
        local tmp = string.byte(input, -left)
        local i   = #arr
        while arr[i] do
            if tmp >= arr[i] then
                left = left - i
                break
            end
            i = i - 1
        end
        cnt = cnt + 1
    end
    return cnt
end

猜你喜欢

转载自blog.csdn.net/heyuchang666/article/details/51832304