This article mainly introduces Lua to get UTF8 string length and string interception and use ... Instead, this article directly gives the implementation code of two functions, the need for friends can refer to the following
First, Lua get UTF8 string length
The code is as follows:
---Get the correct length of the UTF8 encoded string
--@param str
--@return Number
function Utfstrlen (str)
Local len = #str;
Local left = Len;
Local cnt = 0;
Local ARR={0,0XC0,0XE0,0XF0,0XF8,0XFC};
While left ~= 0 do
Local Tmp=string.byte (Str,-left);
Local i= #arr;
While Arr[i] do
If Tmp>=arr[i] then Left=left-i;break;end
I=i-1;
End
cnt=cnt+1;
End
return CNT;
End
Second, the partial length of the given string is intercepted, with the ellipsis "." Replace
The code is as follows:
--@brief cut string and replace tail with "..."
--@param sname: The string to be cut
---@return nMaxCount, String upper, middle text is multiples of 2
---@param nshowcount: Display the number of English words, Chinese text is a multiple of 2, can be empty
--@note function implementation: Intercept the string part, the remainder with "..." Replace
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