用户登录
用户注册

分享至

Lua判断字符串中包含中文字符的方法和计算字符串宽度函数分享

  • 作者: 小疯子娘娘叫你回家喝奶
  • 来源: 51数据库
  • 2021-07-06

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

遍历数组,对每个字节使用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)

软件
前端设计
程序设计
Java相关