lua实现ToCharArry()

  首先介绍一个小技巧,lua在所有的字符串都指向了string为元表,所以我们把字符串的处理逻辑注入string以后

  可以使用"test":doSomeBody()的方式执行,方便很多。

  例:

function string.test()
    print(”简写测试“)
end


local str = "111"

str:test()

  这样也是可以执行的,在全局代码使用中比较方便效率 

  之前偷懒,网上找了几个lua版本ToCharArry()的代码过来用

  结果发现都是只处理1位和3位的情况,导致实际使用过程中无法识别中文符号(因为中文符号是占2位的),紧接着就是读出一堆乱码

  于是查了查编码表

  lua对于中文来说。有2位、3位、4位的站位处理(1位是ascii编码映射) 

  local count =  string.byte(str,1)
  count >= 192 and count < 223    ====>中文符号区
  count>= 224 and count < 239    =====>中文文字区
  count >= 240 and count <= 247 ======>特殊符号区
  于是逻辑就是:
-字符串转换为字符数组
--注入string table里面
function string.toCharArray(str)
    str = str or ""
    local array = {}
    local len = string.len(str)
    while str do
        local fontUTF = string.byte(str,1)

        if fontUTF == nil then
            break
        end

        local byteCount = 0
        if fontUTF > 0 and fontUTF <= 127 then
            byteCount = 1
           elseif fontUTF >= 192 and fontUTF < 223 then
            byteCount = 2
           elseif fontUTF >= 224 and fontUTF < 239 then
            byteCount = 3
           elseif fontUTF >= 240 and fontUTF <= 247 then
            byteCount = 4
          end
          local tmp = string.sub(str,1,byteCount)
            table.insert(array,tmp)
            str = string.sub(str,byteCount + 1,len)
    end
    return array
end

 

posted on 2020-05-04 15:55  年轮下的  阅读(709)  评论(0编辑  收藏  举报

导航