lua 截取中文UTF8字符串

function FormotGameNickName(nickname,len)
    if nickname==nil then
        return ""
    end
    local lengthUTF_8 = #(string.gsub(nickname, "[\128-\191]", ""))
    if lengthUTF_8 <= len then
        return nickname
    else
        local matchStr = "^"
        for var=1, len do
            matchStr = matchStr..".[\128-\191]*"
        end
        local str = string.match(nickname, matchStr)
        return string.format("%s..",str);
    end

end

local nameString = "aaa游客abcdefghijklmnopqrstuvwxyz"

print(FormotGameNickName(nameString,5))--aaa游客..

你可能感兴趣的:(lua)