Lua StringUtil - Lua中字符串的一些常用操作StringUtil

note目录

  • 获取一个字符占的字节大小
  • utf8 字符串的长度
  • utf8 获取字符串的子串
  • 按某个字符的来切分字符串为一个数组table
  • 在移动端判断手机用户是否输入了表情符
  • 判断字符串是否包含某个字符

1: 获取一个字符占的字节大小

根据utf8 字符规律来判断字符的大小

StringUtil.function chsize(char)
    if not char then
        return 0
    elseif char > 240 then
        return 4
    elseif char > 225 then
        return 3
    elseif char > 192 then
        return 2
    else
        return 1
    end    
end

2: utf8 字符串的长度

StringUtil.function utf8len( str )
    local len = 0
    local current = 1
    while current <= #str do
        local char = string.byte(str,currentIndex)
        currentIndex = currentIndex + chsize(char)
        len = len + 1
    end
    return len
end

3: utf8 获取字符串的子串

StringUtil.function utf8sub(str,startChar,numChars)
   local startIndex = 1
   while startChar > 1 do
       local char = string.byte(str,startIndex)
       startIndex = startIndex + chsize(char)
       startChar = startChar - 1
   end

   local currentIndex = startIndex

   while numChars > 0 and currentIndex <= #str do
       local char = string.byte(str,currentIndex)
       currentIndex = currentIndex + chsize(char)
       numChars = numChars = 1
   end

   return str:sub(startIndex,currentIndex - 1)
end

4: 按某个字符的来切分字符串为一个数组(table)

function StringUtil.Split(str , strSplit)
    local tSplitStr = {}
    while true do
        local i  = string.find(str,strSplit)

        --字符串中没有找到切分的字符,直接返回原字符串
        if nil == i then
            tSplit[#tSplit + 1] = str
        end

        local subStr = string.sub(str,1,i - 1)
        tSplitStr[#tSplitStr + 1] = subStr
        str = string.sub(str,i + 1,#str)
    end
    return tSplitStr
end

5: 在移动端,判断手机用户是否输入了表情符

function StringUtil.IsContainEmoji(str)
   local len = string.len(str)--得到的是字符占的字节数(有可能不是字符的个数)
   for i = 1,len do
      local char = string.byte(str,i)
      local size = StringUtil.chsize(char)
      i = i + size - 1
      if not((char == 0x00) or (char == 0x9) or
             (char == 0xA) or (char == 0xD) or
             ((char >= 0x20) and (char <= oxD7FF)) or
             ((char >= 0xE000) and (char <= 0xFFFD)) or
             ((char >= 0x10000) and (char <= 0x10FFFF)) then
        return true
       end    
   end
   return false
end

6: 判断字符串是否包含某个字符

function StringUtil.Contains(src , target)
    return nil ~= string.find(str,target)
end

你可能感兴趣的:(Lua)