Lua字符串中的中英文分割处理
2017-07-14 15:26
447 查看
-- 计算 UTF8 字符串的长度,每一个中文算一个字符 -- @function [parent=#string] utf8len -- @param string input 输入字符串 -- @return integer#integer 长度 --[[-- 计算 UTF8 字符串的长度,每一个中文算一个字符 ~~~ lua local input = "你好World" print(string.utf8len(input)) -- 输出 7 ~~~ ]] -- end -- function string.utf8len(input) local len = string.len(input) local left = len local cnt = 0 local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc} while left ~= 0 do local tmp = string.byte(input, -left) local i = #arr while arr[i] do if tmp >= arr[i] then left = left - i break end i = i - 1 end cnt = cnt + 1 end return cnt end -- lzh -- 功能:将字符串拆成单个字符,存在一个table中 function string.utf8tochars(input) local list = {} local len = string.len(input) local index = 1 local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc} while index <= len do local c = string.byte(input, index) local offset = 1 if c < 0xc0 then offset = 1 elseif c < 0xe0 then offset = 2 elseif c < 0xf0 then offset = 3 elseif c < 0xf8 then offset = 4 elseif c < 0xfc then offset = 5 end local str = string.sub(input, index, index+offset-1) -- print(str) index = index + offset table.insert(list, {byteNum = offset, char = str}) end return list end ---------应用的例子--------- -- 函数功能:字符处理 -- 超30个英文字符长度,后面的用...代替 function Test:ProcessEmailName(content) local chars = string.utf8tochars(content) local nums = 0 local newString = "" for i,v in ipairs(chars or {}) do if v.byteNum>=3 then nums = nums + 2 else nums = nums + 1 end -- 限制超过30个英文字符的长度 -- printLog(nums) if nums <= 30 then newString = newString .. v.char else newString = newString .. "..." break end end return newString end
相关文章推荐
- Lua处理中英文混合字符串
- 第五章 常用Lua开发库2-JSON库、编码转换、字符串处理
- lua 分割字符串
- lua string 分割字符串
- 中英文字符串截取方法, 适用于新闻列表的标题处理
- lua 字符串处理
- 一个字符串分割处理的过程演示
- 常用Lua开发库-JSON库、编码转换、字符串处理
- Lua中用Split函数分割字符串
- lua 分割字符串到table
- js中字符串处理常用的方法(字符分割、字符拼接、截取字符串、是否包含一个字符串)
- guava字符串处理:分割,连接,填充
- cocos Lua 计算中英文字符串长度封装接口
- 截取字符串最后一个字符 && asp textarea 多行数组分割处理
- 165.LeetCode Compare Version Numbers(easy)[字符串处理 分割与int转换]
- Lua中分割字符串
- [寒江孤叶丶的Cocos2d-x之旅_20]Lua字符串分割函数分享,Lua StringSplit
- 处理URL中的中文等字符,计算含有中英文的字符串的长度
- PHP 中英文混合排版中处理字符串常用的函数
- Lua 分割字符串