cocos2d

lua 字符串截断接口(含中文截断)

2018-11-01  本文已影响7人  亮亮同学

cocos2d-x技术群新群:117871561
c++技术交流群:593010226

--去掉符号

function Toolkits:filter_spec_chars(s)
    local ss = {}
    local k = 1
    while true do
        if k > #s then break end
        local c = string.byte(s,k)
        if not c then break end
        if c<192 then
            if (c>=48 and c<=57) or (c>= 65 and c<=90) or (c>=97 and c<=122) then
                table.insert(ss, string.char(c))
            end
            k = k + 1
        elseif c<224 then
            k = k + 2
        elseif c<240 then
            if c>=228 and c<=233 then
                local c1 = string.byte(s,k+1)
                local c2 = string.byte(s,k+2)
                if c1 and c2 then
                    local a1,a2,a3,a4 = 128,191,128,191
                    if c == 228 then a1 = 184
                    elseif c == 233 then a2,a4 = 190,c1 ~= 190 and 191 or 165
                    end
                    if c1>=a1 and c1<=a2 and c2>=a3 and c2<=a4 then
                        table.insert(ss, string.char(c,c1,c2))
                    end
                end
            end
            k = k + 3
        elseif c<248 then
            k = k + 4
        elseif c<252 then
            k = k + 5
        elseif c<254 then
            k = k + 6
        end
    end
    local str = table.concat(ss)
--此判断可忽略
------------------------------
    if str == "" then
       str = "*****"
    end
-------------------------------
    return str
end

--截断 字符串

function Toolkits:ghlBranchStr(str)
    local sNum = 0
    local tab = {}
    for uchar in string.gfind(str, "[%z\1-\127\194-\244][\128-\191]*") do 
        tab[#tab+1] = uchar
        sNum = sNum + 1
    end
    local resultStr = ""
    ---sNum的值就是你想要的长度  我设置为6
    if sNum >= 6 then
       sNum = 6
    end
    for i=1,sNum do
        resultStr = resultStr..tab[i]
    end
    return resultStr
end

--使用

local  str = "欢迎加入我的技术交流群"
if type(str) == "string" then 
        local str_1 = Toolkits:getInstance():filter_spec_chars(str)
        local str_2 = Toolkits:getInstance():ghlBranchStr(str_1)
        print(str)
 end
上一篇下一篇

猜你喜欢

热点阅读