测试代码:
(local s = "①贰a190A#}。!!"是测试用的字符串)
function stringToTable(s)
local tb = {}
--[[
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)只会出现在第二个及随后的编码中(针对多字节编码,如汉字)
]]
for utfChar in string.gmatch(s, "[\1-\127\194-\244][\128-\191]*") do
table.insert(tb, utfChar)
end
return tb
end
local s = "①贰a190A#}。!!"
local sTab = stringToTable(s)
print("总字符个数:"..#sTab)
for i = 1, #sTab do
local outStr = string.format("sTab index:%d,str:\"%s\",Len:%s,byte1:%d,byte2:%d,byte3:%d",
i,
sTab[i],
string.len(sTab[i]),
string.byte(sTab[i]),
string.byte(sTab[i],2) or 0,
string.byte(sTab[i],3) or 0
)
print(outStr)
end
输出结果:
12
总字符个数:12
sTab index:1,str:"①",Len:3,byte1:226,byte2:145,byte3:160
sTab index:2,str:"贰",Len:3,byte1:232,byte2:180,byte3:176
sTab index:3,str:"a",Len:1,byte1:97,byte2:0,byte3:0
sTab index:4,str:"1",Len:1,byte1:49,byte2:0,byte3:0
sTab index:5,str:"9",Len:1,byte1:57,byte2:0,byte3:0
sTab index:6,str:"0",Len:1,byte1:48,byte2:0,byte3:0
sTab index:7,str:"A",Len:1,byte1:65,byte2:0,byte3:0
sTab index:8,str:"#",Len:1,byte1:35,byte2:0,byte3:0
sTab index:9,str:"}",Len:1,byte1:125,byte2:0,byte3:0
sTab index:10,str:"。",Len:3,byte1:227,byte2:128,byte3:130
sTab index:11,str:"!",Len:3,byte1:239,byte2:188,byte3:129
sTab index:12,str:"!",Len:1,byte1:33,byte2:0,byte3:0