数码资讯
Lua utf8字符处理
UTF8的编码规则:
1. 字符的第一个字节范围: 0x00—0x7F(0-127),或者 0xC2—0xF4(194-244); UTF8 是兼容 ascii 的,所以 0~127 就和 ascii 完全一致
2. 0xC0, 0xC1,0xF5—0xFF(192, 193 和 245-255)不会出现在UTF8编码中
3. 0x80—0xBF(128-191)只会出现在第二个及随后的编码中(针对多字节编码,如汉字)
这样我们可以利用lua强大的模式匹配,来实现我们要的效果,关键的处理有这么两个:
1. local _, count = string.gsub(str, "[^128-193]", ""),用来得到str中的字符数
2. for uchar in string.gfind(str, "[%z1-127194-244][128-191]*") do tab[#tab+1] = uchar end,用来把str中的每个字符映射到tab中
再给出两个例子:
-- 计算字符串宽度
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)
--字符串分割函数 --传入字符串和分隔符,返回分割后的table function _str_split(str, delim) if type(delim) ~= "string" or string.len(delim) <= 0 then ailog.e("delim[%s] is invalid!", delim) return end local start_pos = 1 local end_pos, delim_pos = nil, nil local sub_str = nil local result = {} while true do delim_pos = string.find(str, delim, start_pos, true) if not delim_pos then break end end_pos = delim_pos - 1 if start_pos <= end_pos then sub_str = string.sub(str, start_pos, end_pos) table.insert(result, sub_str) end start_pos = delim_pos + string.len(delim) end sub_str = string.sub(str, start_pos) if start_pos < string.len(str) then table.insert(result, sub_str) end return result end a = split("我们的中国.就是一个家.wom的.ni", ".") for k, v in ipairs(a) do print(k, v) end