得到指定占用宽度的字体 。(英文占用一个位,中文占用两个位,英文大写占用两个位)

---检查字符是否为英文
function charIsEn(char)
local b = string.byte(char, 1)
return b < 0x80
end

---检查字符否为大写
function charUpperEn(char)
local b = string.byte(char, 1)
return b < 0x80 and b > 0x40 and b < 0x5b;
end

--"口香糖除あなたのお母さんの卵了提升艺术气Tôi hẹn hò với em gái của bạn质外口香糖除了提升艺术气质外"
--PS:为了保证字符的可用性,可能会比要求的长一个占位空间
function string.getSolidLen(utfstr,outSolidLen)
local counter = 1;
local outstr="";
while counter <= #utfstr do
local len = 0;
--单个字符的字节长度
local b = string.byte(utfstr, counter);
if b<0xC0 then len = 1;
elseif b<0xE0 then len = 2;
elseif b<0xF0 then len = 3;
elseif b<0xF8 then len = 4;
elseif b<0xFC then len = 5;
else len = 6;
end

local char = string.sub(utfstr,counter,counter + len - 1);

if charIsEn(char) == true and charUpperEn(char) == false then
outSolidLen = outSolidLen - 1;
else
outSolidLen = outSolidLen - 2;
end
outstr = outstr..char;
counter = counter + len
if outSolidLen <= 0 then break end
end
return outstr
end

function outTest( ... )
local str1 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",1);
local str2 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",2);
local str3 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",3);
local str4 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",4);
local str5 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",5);
local str6 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",6);
local str7 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",7);
local str8 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",8);
local str9 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",9);
local str10 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",10);
local str11 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",11);
local str12 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",12);
local str13 = string.getSolidLen("口香糖1除bABCDEFgHiGKLM",13);
print(str1);
print(str2);
print(str3);
print(str4);
print(str5);
print(str6);
print(str7);
print(str8);
print(str9);
print(str10);
print(str11);
print(str12);
print(str13);
end

outTest();

posted @ 2017-05-31 10:10  czjone  阅读(390)  评论(0编辑  收藏  举报