lua中如何判断字符串中包含中文字符?

如题:类似AS3中的charCodeAt方法.貌似string.byte()不行.http://anyexxx.diandian.com/post/2013-07-30/40053147587这里可以正确取出但是还是不知道某个字符是中文的.望大神解答..

-- 计算字符串宽度

local str = "Jimmy: 你好,世界!"
local fontSize = 20
local lenInByte = #str
local width = 0

for i=1,lenInByte do
    local curByte = string.byte(str, i)
    local byteCount = 1;
    if curByte>0 and curByte<=127 then
        byteCount = 1
    elseif curByte>=192 and curByte<223 then
        byteCount = 2
    elseif curByte>=224 and curByte<239 then
        byteCount = 3
    elseif curByte>=240 and curByte<=247 then
        byteCount = 4
    end
    
    local char = string.sub(str, i, i+byteCount-1)
    i = i + byteCount -1
    
    if byteCount == 1 then
        width = width + fontSize * 0.5
    else
        width = width + fontSize
        print(char)
    end
end

print("总宽度: "..width)


```


从
i7909的richlabel里抄出来的~ :7::7:


你可以直接在这里运行 http://ideone.com/bOpT5p


运行结果
你
好
世
界
总宽度: 270


```

遍历数组,对每个字节使用string.byte(),发现有大于127的,就是汉字

我以為跟AS3一樣的.是判斷0x4e00和0x9fbb之間.原來只要大於127就行.多謝各位了.

大于127是有问题的“¥”这个符号也是大于127的

这个符号就是中文符号啊

楼主 解决没有阿 不知地 楼主 说怎么 区别出 中文和 中文字符 的?

沙发不是已经给出方法了吗?

– mark –

有用,谢大神普及姿势

沙发会有bug for循环会把i从1到长度都算过一遍 2个汉字被计算成80的宽度
function countStrLength( str )
local fontSize = 20
local lenInByte = #str
local width = 0
local i = 1
while true do
if i <= lenInByte then
local curByte = string.byte(str, i)
if curByte>0 and curByte<=127 then
byteCount = 1
elseif curByte>=192 and curByte<223 then
byteCount = 2
elseif curByte>=224 and curByte<239 then
byteCount = 3
elseif curByte>=240 and curByte<=247 then
byteCount = 4
end
local char = string.sub(str, i, i+byteCount-1)
i = i + byteCount
if byteCount == 1 then
width = width + fontSize * 0.5
else
width = width + fontSize
end
else
break
end
end
return width
end

不好用啊 总说 local curByte = string.byte(str, i) 有问题

报错信息:37: unexpected symbol near ‘?’

沙发的方法有问题
1.lua循环中i只会自增1
2.为什么 i = i + byteCount -1 截取字符串的时候这么写对 但是算下一个index就应该 i = i + byteCount
所以10楼的方法是正解