Lua实现方法:
```
---@param str string
---@return number
function StringUtils.GetStringCharCount(str, subNum)
local charCount =0
local subStr =str
local lenInByte = #str
local i =1
while (i <= lenInByte)do
local curByte =string.byte(str, i)
local byteCount =1;
if curByte >0 and curByte <=127 then
byteCount =1 --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 --4字节字符
end
if type(subNum) =="number" and subNum == charCount +1 then
subStr =string.sub(str, 0, i + byteCount -1)
end
--Log('[StringUtils] GetStringCharCount' .. string.sub(str, i, i + byteCount - 1))
--Log('[StringUtils] GetStringCharCount' .. string.sub(str, 0, i + byteCount - 1))
i = i + byteCount-- 重置下一字节的索引
charCount = charCount +1 -- 字符的个数(长度)
end
return charCount, subStr
end
```
C#计算半角外语文字
///输入字符串,计算全角字符数向上取整,两个半角算一个全角字符,三字节的算半角字符(泰语)
```
public static int CalcLength(string strContent)
{ if (isCN)
{
return strContent.Length;
}
else
{
return (CalcLengthOversea(strContent) + 1)/2;
}
}
private static int CalcLengthOversea(string strContent)
{ int strLength = 0;
for (int i = 0; i < strContent.Length; i++)
{
char c = strContent[i];
bool bThaiChar = c >= '\x0E00' && c <= '\x0E7F';
if (bThaiChar)
{
//泰语字符强制视为1个字符
strLength += 1;
}
else
{
string subStr = strContent.Substring(i, 1);
int length = System.Text.Encoding.UTF8.GetByteCount(subStr);
if (length >= 3)
{
strLength += 2;
}
else
{
strLength += 1;
}
}
}
return strLength;
}
```