美文网首页cocos2d-Lua
lua 同时 截取中文和英文字符串处理

lua 同时 截取中文和英文字符串处理

作者: 人气小哥 | 来源:发表于2017-08-29 11:46 被阅读27次

    原文: http://blog.csdn.net/fenrir_sun/article/details/52232723

    lua 用

    string.sub("大", 1, 1)--结果乱码
    

    所以有了以上这个需求

    全局函数

    
    function SubStringUTF8(str, startIndex, endIndex)
        if startIndex < 0 then
            startIndex = SubStringGetTotalIndex(str) + startIndex + 1;
        end
    
        if endIndex ~= nil and endIndex < 0 then
            endIndex = SubStringGetTotalIndex(str) + endIndex + 1;
        end
    
        if endIndex == nil then 
            return string.sub(str, SubStringGetTrueIndex(str, startIndex));
        else
            return string.sub(str, SubStringGetTrueIndex(str, startIndex), SubStringGetTrueIndex(str, endIndex + 1) - 1);
        end
    end
    
    --获取中英混合UTF8字符串的真实字符数量
    function SubStringGetTotalIndex(str)
        local curIndex = 0;
        local i = 1;
        local lastCount = 1;
        repeat 
            lastCount = SubStringGetByteCount(str, i)
            i = i + lastCount;
            curIndex = curIndex + 1;
        until(lastCount == 0);
        return curIndex - 1;
    end
    
    function SubStringGetTrueIndex(str, index)
        local curIndex = 0;
        local i = 1;
        local lastCount = 1;
        repeat 
            lastCount = SubStringGetByteCount(str, i)
            i = i + lastCount;
            curIndex = curIndex + 1;
        until(curIndex >= index);
        return i - lastCount;
    end
    
    --返回当前字符实际占用的字符数
    function SubStringGetByteCount(str, index)
        local curByte = string.byte(str, index)
        local byteCount = 1;
        if curByte == nil then
            byteCount = 0
        elseif curByte > 0 and curByte <= 127 then
            byteCount = 1
        elseif curByte>=192 and curByte<=223 then
            byteCount = 2
        elseif curByte>=224 and curByte<=239 then
            byteCount = 3
        elseif curByte>=240 and curByte<=247 then
            byteCount = 4
        end
        return byteCount;
    end
    

    具体使用

        local szHhName = "大风兄弟"
        local szHhName2 = "aaa"
        local szHhName2 = "AAA"
        local szHhOne = SubStringUTF8(szHhName2, 1, 1)--结果"大"
        self.m_Label_FlagName:setString(szHhOne)
    

    相关文章

      网友评论

        本文标题:lua 同时 截取中文和英文字符串处理

        本文链接:https://www.haomeiwen.com/subject/inrodxtx.html