lua string.sub截取中英文

cocos2dx 2.x环境,要做一个截取很长的字符串的前100个字符显示的小功能。

PC环境ok,出了ios包发现有时候这个字符串会显示不出,猜测了下可能是跟中文字在lua里每个字占3个字符有关,举个例子:文章来源地址https://www.yii666.com/article/758365.html网址:yii666.com<

原字符串"一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十",第100个字符是第四组第一个“一”的第一个字符,PC上显示会是一个小乱码,真机上可能就显示不正常了。

 local function getByteCount(str, index)
local curByte = string.byte(str, index)
local byteCount = "not found"
if curByte == nil then
byteCount =
elseif curByte > and curByte <= then
byteCount =
elseif curByte>= and curByte<= then
byteCount =
elseif curByte>= and curByte<= then
byteCount =
elseif curByte>= and curByte<= then
byteCount =
end
return byteCount;
end

getByteCount返回str的第index个字符实际占用的字符数,不在以上ifelse判断区间的返回"not found"(如一这个中文字的第二第三字符,第一个字符落在224~239这个区间所以会返回3)。

 local function findByteWholeEnd(str, index)
local i = index
local curByteCount
while true do
curByteCount = getByteCount(str, index)
if curByteCount == "not found" then
i = i -
else
break
end
end
return i + curByteCount -
end

findByteWholeEnd可以找出占用多个字符的中文字(或其他)的实际结尾在哪儿,while循环里如果当前字符是not found则再往前找。文章来源地址:https://www.yii666.com/article/758365.html

用的时候:文章地址https://www.yii666.com/article/758365.html

 if string.len(str) >  then
local wholeEnd = findByteWholeEnd(str, )
lab:setString(string.sub(str, , wholeEnd))
else
lab:setString(str)
end

这样就不是精准的前100个字符,而是能完整显示的前100+X个字符。网址:yii666.com

版权声明:本文内容来源于网络,版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。文本页已经标记具体来源原文地址,请点击原文查看来源网址,站内文章以及资源内容站长不承诺其正确性,如侵犯了您的权益,请联系站长如有侵权请联系站长,将立刻删除

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信图片_20190322181744_03.jpg

微信扫一扫打赏

请作者喝杯咖啡吧~

支付宝扫一扫领取红包,优惠每天领

二维码1

zhifubaohongbao.png

二维码2

zhifubaohongbao2.png