方法一:
--- 获取字符宽度(中文算2个字符)
--
-- @param string str 原始字符串
-- @return number 字符宽度
function Util.Strlen(str)
local bytes = { string.byte(str, 1, #str) }
local length, begin = 0, false
for _, byte in ipairs(bytes) do
if byte < 128 or byte >= 192 then
begin = false
length = length + 1
elseif not begin then
begin = true
length = length + 1
end
end
return length
end
方法二:
local len = (utf8.len(str) + string.len(str))/2
本文介绍了两种计算字符串宽度的方法,第一种使用Lua语言通过分析字符串的字节来判断每个字符是否为全角字符(如中文),并据此计算总宽度;第二种方法利用UTF-8编码特性,结合string.len()函数,得出更为简洁的实现方案。
23

被折叠的 条评论
为什么被折叠?



