lua怎么判断字符串中含有汉字

如题所述

一、判断字符串中包含中文字符的方法

遍历数组,对每个字节使用string.byte(),发现有大于127的,就是汉字,可以参照下面的代码。

二、计算字符串宽度函数
计算字符串宽度

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)
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-03-25
a='hgsadg我们hdsfk'
l=strlen(a)
for i=1,l do
asc2=strbyte(strsub(a,i,i))
if asc2>127 then
print('可能是汉字')
else
print(strchar(asc2))
end
end

追答

注:lua4的脚本。若是lua5,请在内部函数之前加上'string.'

本回答被提问者采纳
相似回答