一、lua获取utf8字符串长度
二、截取给定字符串的部分长度,超出部分用省略号“.”替换
function getshortname(sname,nmaxcount,nshowcount)
if sname == nil or nmaxcount == nil then
return
end
local sstr = sname
local tcode = {}
local tname = {}
local nleninbyte = #sstr
local nwidth = 0
if nshowcount == nil then
nshowcount = nmaxcount - 3
end
for i=1,nleninbyte do
local curbyte = string.byte(sstr, i)
local bytecount = 0;
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 = nil
if bytecount > 0 then
char = string.sub(sstr, i, i+bytecount-1)
i = i + bytecount -1
end
if bytecount == 1 then
nwidth = nwidth + 1
table.insert(tname,char)
table.insert(tcode,1)
elseif bytecount > 1 then
nwidth = nwidth + 2
table.insert(tname,char)
table.insert(tcode,2)
end
end
if nwidth > nmaxcount then
local _sn = ""
local _len = 0
for i=1,#tname do
_sn = _sn .. tname[i]
_len = _len + tcode[i]
if _len >= nshowcount then
break
end
end
sname = _sn .. "..."
end
return sname
end
如对本文有疑问, 点击进行留言回复!!
网友评论