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

PC环境ok,出了ios包发现有时候这个字符串会显示不出,猜测了下可能是跟中文字在lua里每个字占3个字符有关,举个例子:

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

 1 local function getByteCount(str, index)
 2     local curByte = string.byte(str, index)
 3     local byteCount = "not found"
 4     if curByte == nil then
 5         byteCount = 0
 6     elseif curByte > 0 and curByte <= 127 then
 7         byteCount = 1
 8     elseif curByte>=192 and curByte<=223 then
 9         byteCount = 2
10     elseif curByte>=224 and curByte<=239 then
11         byteCount = 3
12     elseif curByte>=240 and curByte<=247 then
13         byteCount = 4
14     end
15     return byteCount;
16 end

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

 1 local function findByteWholeEnd(str, index)
 2     local i = index
 3     local curByteCount
 4     while true do
 5         curByteCount = getByteCount(str, index)
 6         if curByteCount == "not found" then
 7             i = i - 1
 8         else
 9             break
10         end
11     end  
12     return i + curByteCount - 1  
13 end

findByteWholeEnd可以找出占用多个字符的中文字(或其他)的实际结尾在哪儿,while循环里如果当前字符是not found则再往前找。

用的时候:

1 if string.len(str) > 100 then
2     local wholeEnd = findByteWholeEnd(str, 100)
3     lab:setString(string.sub(str, 1, wholeEnd))
4 else
5     lab:setString(str)
6 end

这样就不是精准的前100个字符,而是能完整显示的前100+X个字符。

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!