function GetCharNewStrByLimit(str,limitCharNum)
local bytes = {str:byte(1,#str)}
local length,begin,cutByteLength = 0,false,0
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
if length > limitCharNum then
cutByteLength = cutByteLength - 1
end
else
if length > limitCharNum then
cutByteLength = cutByteLength + 1
end
end
if length <= limitCharNum then
cutByteLength = cutByteLength + 1
else
break
end
end
return string.sub(str,1,cutByteLength)
end
lua获取限制字数后的字符串
最新推荐文章于 2023-02-24 10:54:20 发布
该函数`GetCharNewStrByLimit`用于处理UTF-8编码的字符串,根据限制的字符数进行截取。它遍历字符串的字节,区分单字节和多字节字符,确保截取过程中不中断多字节字符。适用于需要限制输出文本长度的场景。
2849

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



