Lua判断字符串中包含中文字符的方法和计算字符串宽度函数分享
一、判断字符串中包含中文字符的方法
遍历数组,对每个字节使用string.byte(),发现有大于127的,就是汉字,可以参照下面的代码。
二、计算字符串宽度函数
--计算字符串宽度
localstr="Jimmy:你好,世界!"
localfontSize=20
locallenInByte=#str
localwidth=0
fori=1,lenInBytedo
localcurByte=string.byte(str,i)
localbyteCount=1;
ifcurByte>0andcurByte<=127then
byteCount=1
elseifcurByte>=192andcurByte<223then
byteCount=2
elseifcurByte>=224andcurByte<239then
byteCount=3
elseifcurByte>=240andcurByte<=247then
byteCount=4
end
localchar=string.sub(str,i,i+byteCount-1)
i=i+byteCount-1
ifbyteCount==1then
width=width+fontSize*0.5
else
width=width+fontSize
print(char)
end
end
print("总宽度:"..width)