您的位置:首页 > 编程语言 > Lua

lua截取指定长度字符(包含中文)

2017-12-20 17:57 267 查看
 

--  分离字符
function AppInfo: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
 
-- 计算字符数
function AppInfo:GetUTFLen(s)  
    local sTable =  self:StringToTable(s)  
  
    return #sTable  
end

-- 获取指定字符个数的字符串的实际长度
function AppInfo:GetUTFLenWithCount(s, count)  
    local sTable =  self: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 + utfCharLen  
        
         count = count -1

         if count <= 0 then  
             break  
         end  
    end  
  
    return len  
end  

-- 截取指定长度
function AppInfo:GetMaxLenString(s, maxLen)  
    local len =  self:GetUTFLen(s)  
      
    local dstString = s  
    -- 超长,裁剪,加...  
    if len > maxLen then  
        dstString = string.sub(s, 1, self:GetUTFLenWithCount(s, maxLen))  
        dstString = dstString.."..."  
    end  
  
    return dstString  
end  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: