参考博客:UTF8字符串在lua的截取和字数统计【转载】

需求

按字面个数来截取子字符串
函数(字符串, 开始位置, 截取长度)

utf8sub("你好1世界哈哈",,)    =    好1世界哈
utf8sub("1你好1世界哈哈",,) = 你好1世界
utf8sub("你好世界1哈哈",,) = 你好世界1
utf8sub("",,) =
utf8sub("øpø你好pix",,) = pø你好p

错误方法

网上找了一些算法, 都不太正确; 要么就是乱码, 要么就是只考虑了4 byte 中文的情况, 不够全面

1. string.sub(s,1,截取长度*4)

  网上很多直接使用"`""string.sub(s,1,截取长度*4)`"是肯定不对的, 因为如果中英文混合的字符串, 例如`你好1世界`的字符长度分别是`4,4,1,4,4`, 如果截取4个字, 4*4=4+4+1+4+3, 那`世界`的`界`字将会被取前3个byte, 就会出现乱码

2. if byte>128 then index = index + 4

问题关键

1. utf8字符是变长字符

2. 字符长度有规律

如文字符编码中所列,utf-8是对unicode字符集的编码方案。因此其变长编码方式为:

一字节:0*******

两字节:110*****,10******

三字节:1110****,10******,10******

四字节:11110***,10******,10******,10******

五字节:111110**,10******,10******,10******,10******

六字节:1111110*,10******,10******,10******,10******,10******

因此,拿到字节串后,想判断UTF8字符的byte长度,按照上文的规律,只需要获取该字符的首个Byte,根据其值就可以判断出该字符由几个Byte表示。

其代码如下:

local funciton charsize(ch)
if not ch then return
elseif ch >= then return
elseif ch >= and ch < then return
elseif ch >= and ch < then return
elseif ch >= and ch < then return
elseif ch >= and ch < then return
elseif ch < then return
end
end
-- 计算utf8字符串字符数, 各种字符都按一个字符计算
-- 例如utf8len("1你好") => 3
function utf8len(str)
local len =
local aNum = --字母个数
local hNum = --汉字个数
local currentIndex =
while currentIndex <= #str do
local char = string.byte(str, currentIndex)
local cs = charsize(char)
currentIndex = currentIndex + cs
len = len +
if cs == then
aNum = aNum +
elseif cs >= then
hNum = hNum +
end
end
return len, aNum, hNum
end
-- 截取utf8 字符串
-- str: 要截取的字符串
-- startChar: 开始字符下标,从1开始
-- numChars: 要截取的字符长度
function utf8sub(str, startChar, numChars)
local startIndex =
while startChar > do
local char = string.byte(str, startIndex)
startIndex = startIndex + chsize(char)
startChar = startChar -
end local currentIndex = startIndex while numChars > and currentIndex <= #str do
local char = string.byte(str, currentIndex)
currentIndex = currentIndex + chsize(char)
numChars = numChars -
end
return str:sub(startIndex, currentIndex - )
end -- 自测
function test()
-- test utf8len
assert(utf8len("你好1世界哈哈") == )
assert(utf8len("你好世界1哈哈 ") == )
assert(utf8len(" 你好世 界1哈哈") == )
assert(utf8len("") == )
assert(utf8len("øpø你好pix") == ) -- test utf8sub
assert(utf8sub("你好1世界哈哈",,) == "好1世界哈")
assert(utf8sub("1你好1世界哈哈",,) == "你好1世界")
assert(utf8sub(" 你好1世界 哈哈",,) == "你好1世界 ")
assert(utf8sub("你好世界1哈哈",,) == "你好世界1")
assert(utf8sub("",,) == "")
assert(utf8sub("øpø你好pix",,) == "pø你好p") print("all test succ")
end test()

Lua截取utf-8编码的中英文混合字符串的更多相关文章

  1. PHP获取中英文混合字符串长度及截取

    1.字符串长度 PHP获取中英文混合字符串长度的实现代码如下,1中文=1位,2英文=1位,可自行修改 /** * PHP获取字符串中英文混合长度 * @param $str string 字符串 *  ...

  2. CSS截取中英文混合字符串长度

    <!doctype html> <html> <head> <meta http-equiv="content-type" content ...

  3. 用C#截取指定长度的中英文混合字符串

    很早以前写过一篇文章(用C#截取指定长度的中英文混合字符串),但是对性能没有测试,有人说我写的这个方法性能有问题,后来想,可能真会有BT之需求要求传入一个几万K甚至几M体积的字符串进来,那将会影响正则 ...

  4. c#的中英文混合字符串截取

    public class StringHelper     {         public static string GetSubString(string str, int len)       ...

  5. c#的中英文混合字符串截取 public static string SubString(string inputString, int byteLength)

    /// <summary>        /// c#的中英文混合字符串截取(区分中英文)        /// </summary>        /// <param ...

  6. c#的中英文混合字符串截取指定长度,startidx从0开始

    //c#的中英文混合字符串截取指定长度,startidx从0开始 by gisoracle@126.com public string getStrLenB(string str, int start ...

  7. C#与JS实现 获取指定字节长度 中英文混合字符串 的方法

    平时在作数据库插入操作时,如果用 INSERT 语句向一个varchar型字段插入内容时,有时会因为插入的内容长度超出规定的长度而报错. 尤其是插入中英文混合字符串时,SQL Server中一般中文要 ...

  8. 中英文混合字符串截取java

    //截取字符串长度(中文2个字节,半个中文显示一个) public String subTextString(String str,int len){ if(str.length()<len/2 ...

  9. 用JS来实现于截取中英文混合字符串方法(转载)

    网站制作过程中,提示层文字超出,需要JS做字符串截取,但是呢,我们常常会烦恼文字中英文混合如何判断,因为我们知道在JS中 string.length这个值是不考虑中英文的,但是计算机对中英文的识别是  ...

随机推荐

  1. MyBatis源码分析(1)-MapConfig文件的解析

    1.简述 MyBatis是一个优秀的轻ORM框架,由最初的iBatis演化而来,可以方便的完成sql语句的输入输出到java对象之间的相互映射,典型的MyBatis使用的方式如下: String re ...

  2. (状压) Brush (IV) (Light OJ 1018)

    http://www.lightoj.com/volume_showproblem.php?problem=1018   Mubashwir returned home from the contes ...

  3. nginx实现访问网站或目录密码认证保护

    添加目录登陆认证 location / { auth_basic "提示"; auth_basic_user_file /usr/conf/htpasswd; } auth_bas ...

  4. Windows上成功编译CoreCLR源代码

    昨天得知微软在GitHub上发布CoreCLR的源代码之后,立马从GitHub上签出代码,并尝试在Windows Server 2012上进行编译. 参考CoreCLR的开发者指南(Developer ...

  5. linux下svn定时更新项目

    方法一.用shell脚本定时更新项目   1.进入网站的根目录,假设项目位置放在/var/www/test cd /var/www/test   2.建立脚本文件update.sh,分两步进行.首先利 ...

  6. 使用window2003安装邮件服务器最新实际操作记录

    关于使用windows 2003自带的服务组件来安装简单的pop3 协议邮件服务器网上教程很多,可以搜索出来,就是安装IIS选中smtp和添加window是组件的应用程序服务器,这点这里不多说. 安装 ...

  7. [BTS] The value "" for the property InboundId is invalid

    Microsoft.ServiceModel.Channels.Common.MetadataException: Retrieval of Operation Metadata has failed ...

  8. win32汇编hello world

    下载:http://www.masm32.com/ 安装masm32 建一个Var.bat文件并运行 @echo offset include=E:\masm32\includeset lib=E:\ ...

  9. cookie入门与学习

    据我对cookie诞生背景的了解,cookie是由网景公司创建的,目的就是将用户的数据储存在客户端上.伴随的HTML5的出现,现在又有另外一个解决数据离线储存的方案,就是HTML5中的Web stor ...

  10. GPU---并行计算利器

    转载请引用:GPU---并行计算利器 源于阿里巴巴CCO<猿来如此>分享 1 GPU是什么 如图1所示,这台PC机与普通PC机不同的是这里插了7张显卡,左下角是显卡,在中间的就是GPU芯片 ...