lua截取指定长度字符(包含中文)
2017-12-20 17:57
267 查看
-- 分离字符
function AppInfo: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, "[%z\1-\127\194-\244][\128-\191]*") do
table.insert(tb, utfChar)
end
return tb
end
-- 计算字符数
function AppInfo:GetUTFLen(s)
local sTable = self:StringToTable(s)
return #sTable
end
-- 获取指定字符个数的字符串的实际长度
function AppInfo:GetUTFLenWithCount(s, count)
local sTable = self:StringToTable(s)
local len = 0
local charLen = 0
for i=1,#sTable do
local utfCharLen = string.len(sTable[i])
if utfCharLen > 1 then -- 长度大于1的就认为是中文
charLen = 2
else
charLen = 1
end
len = len + utfCharLen
count = count -1
if count <= 0 then
break
end
end
return len
end
-- 截取指定长度
function AppInfo:GetMaxLenString(s, maxLen)
local len = self:GetUTFLen(s)
local dstString = s
-- 超长,裁剪,加...
if len > maxLen then
dstString = string.sub(s, 1, self:GetUTFLenWithCount(s, maxLen))
dstString = dstString.."..."
end
return dstString
end
相关文章推荐
- 从一个包含汉字和其他字符的字符串中截取指定字节长度的字符串,不可以出现中文乱码
- lua 含中文的字符串处理--分离字符、计算字符数、截取指定长度
- 截取字符串 包含中文处理,一个中文字符等于2个长度
- 截取指定的字符长度(其中字符串中有中文,如果有半个中文则去掉)
- 【转载】C# 字符串截取指定长度的中文字符--精点
- 根据指定字符长度截取字符串(包含中英文)
- 按长度截取包含中文字符的字符串
- php 截取指定长度中文字符
- js实现超过长度的字符截取指定长度(中文字符算2个字符),超出部分以...显示
- *方法说明:截取指定长度的字符串并在末尾加入指定字符
- 截取指定长度文字,超出部分以特定字符代替
- Java精确截取字符串/获取字符串前指定长度字符函数
- lua中文字符串长度计算和截取
- sql计算字符串中包含中文、英文字符长度
- 判断一个字符串包含某个字符/截取指定字符窜
- C#中进行中英文字符截取(中文2个长度,英文1个)
- net截取指定长度汉字超出部分以指定的字符代替
- 正则表达式判断是否存在中文和全角字符和判断包含中文字符串长度
- 获取包含中文字符串的长度、截取包含中文的字符串
- php从mysql字段中截取指定长度字符汉字代码