Lua&&C#计算字符个数

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;

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容