Lua utf8中文字符个数和子串截取
2017-06-18 18:19
2146 查看
note 目录
utf8 字符规律utf8 中文字符的大小(占多少个字节)
utf8 字符串的长度
utf8 获取字符串的子串
测试example
1: utf8 字符规律
字符串的首个byte表示了该utf8字符的长度utf8单个字符可以有4种字节来存储:1个字节,2个字节,3个字节,4个字节。
如果第一个一个字节的第一位为0,那么代表当前字符为单字节字符,占用1个字节的空间。
如果第一个一个字节以110开头,那么代表当前字符为双字节字符,占用2个字节的空间。
如果第一个一个字节以1110开头,那么代表当前字符为三字节字符,占用3个字节的空间。
如果第一个一个字节以11110开头,那么代表当前字符为四字节字符,占用4个字节的空间。
[b]1.1 1个字节[/b]
0xxxxxxx - 1 byte
第一位为0,后面7位可以是任意的,则最大的值为:01111111 —> 127
[b]1.2 2个字节[/b]
110xxxxx - 192, 2 byte
前3为固定为110,则最最小为:11000000 —> 192
[b]1.3 3个字节[/b]
1110xxxx - 225, 3 byte
前4为固定为1110,则最最小为:11100000 —> 225
[b]1.4 4个字
4000
节[/b]
11110xxx - 240, 4 byte
前5为固定为11110,则最最小为:11110000 —> 240
2: 中文字符的大小(占多少个字节)
local 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
3: utf8 字符串的长度
local 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
4: utf8 获取字符串的子串
local 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
5: 测试example
print(utf8len("好好学习1天天向上")) ---> 9 print(utf8sub("好好学习1天天向上",5,2)) ---> 1天
最后
关于UTF-8介绍参考wiki词条:https://en.wikipedia.org/wiki/UTF-8
相关文章推荐
- Golang中获取中文字符串的子串字符位置及截取子串
- 输入字符串和字节数,截取子串(串中含有中文字符)
- php实现中文字符截取防乱码方法汇总
- JS/Jquery 截取字符串中的中文字符 && 判断数组中是否还有某个字符串
- PHP中文字符截取
- C#中文字符截取函数
- smarty截取中文字符乱码问题?gb2312-------utf-8
- PHP截取字符串,获取长度,获取字符位置的函数 中文字符截取
- js实现超过长度的字符截取指定长度(中文字符算2个字符),超出部分以...显示
- lua 含中文的字符串处理--分离字符、计算字符数、截取指定长度
- 【JS】JS判断字符输入个数(数字英文长度记为1,中文记为2,超过长度自动截取)
- 字符截取,解决中文的截取问题
- Avalon中文长字符截取、关键字符隐藏、自定义过滤器
- (Delphi中处理字符串)截取中文字符和英文字符,去除所有数字
- smarty截取中文字符乱码问题解决方案(兼容中英文双编码)
- 中文字符截取乱码问题
- 解决截取中文字符出现乱码的函数
- 截取中文字符长度(中文、字母都有效)
- 前几天遇到的一个面试题,关于中文字符截取的问题。IO流的应用
- 字符截取,解决中文的截取问题