cocos2dx 2.x环境,要做一个截取很长的字符串的前100个字符显示的小功能。
PC环境ok,出了ios包发现有时候这个字符串会显示不出,猜测了下可能是跟中文字在lua里每个字占3个字符有关,举个例子:
原字符串"一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十一二三四五六七八九十",第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