中文截取问题

本文介绍了一种在Lua中实现的UTF-8字符串截取算法,该算法能够根据指定长度对包含中文和英文字符的字符串进行精确截取,并可选择性地在截取后的字符串末尾添加省略号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

--- 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  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值