中文截取问题

--- s 需要截取的字符串
--- max 截取的长度

--- hasEnding 是否需要添加省略号


local function GetUTFLen(s)
    local sTable = StringToTable(s)
    local len = 0
    local charLen = 0
    for i = 1, #sTable do
        local utfCharLen = string.len(sTable[i])
        if utfCharLen > 1 then
            -- 长度大于1的就认为是中文
            charLen = 2
        else
            charLen = 1
        end
        len = len + charLen
    end
    return len

end

 local function StringToTable(s)

    local tb = { }
    --[[
    UTF8的编码规则:
    1. 字符的第一个字节范围: 0x00—0x7F(0-127),或者 0xC2—0xF4(194-244); UTF8 是兼容 ascii 的,所以 0~127 就和 ascii 完全一致
    2. 0xC0, 0xC1,0xF5—0xFF(192, 193 和 245-255)不会出现在UTF8编码中
    3. 0x80—0xBF(128-191)只会出现在第二个及随后的编码中(针对多字节编码,如汉字)
    ]]
    for utfChar in string.gmatch(s, "[%z\1-\127\194-\244][\128-\191]*") do
        table.insert(tb, utfChar)
    end
    return tb
end 

local function GetUTFLenWithCount(strText, length)
    local sTable = StringToTable(strText)
    local len = 0
    local charLen = 1
    local isLimited =(length >= 0)
    for i = 1, #sTable do
        local utfCharLen = string.len(sTable[i])
        if utfCharLen > 1 then
            -- 长度大于1的就认为是中文
            charLen = 2
        else
            charLen = 1
        end
        len = len + utfCharLen
        if isLimited then
            length = length - charLen
            if length <= 0 then
                break
            end
        end
    end
    return len

end


function GetMaxLenString(s, maxLen, hasEnding)

    local len = GetUTFLen(s)

    local dstString = s
    -- 超长,裁剪,加...
    if len > maxLen then
        dstString = string.sub(s, 1, GetUTFLenWithCount(s, maxLen))
        if hasEnding then
            dstString = dstString .. "..."
        end
    end
    return dstString
end  

猜你喜欢

转载自blog.csdn.net/xuefujin/article/details/80924961