string字节长度

2023-03-12  本文已影响0人  叫我颜先生
string字节长度 & 限制string字节长度

例如:EllipsisString("人a1_——打", 7, "...")(—— 与 - 不一样,里面的是中文的破折号)

输出:人a1_—...

public static string EllipsisString(string value, int limit, string ellipsis)
    {
        string outputStr = value;
        outputStr = LimitStringByUTF8(value, limit) + (CheckStringByUTF8(value, limit + 1) ? ellipsis : "");
        return outputStr;
    }
    public static bool CheckStringByUTF8(string temp, int limit)
    {
        bool overflow = false;
        int count = 0;

        for (int i = 0; i < temp.Length; i++)
        {
            string tempStr = temp.Substring(i, 1);
            int byteCount = System.Text.ASCIIEncoding.UTF8.GetByteCount(tempStr);
            if (byteCount > 1)
            {
                count += 2;
            }
            else
            {
                count += 1;
            }
            if (count >= limit)
            {
                overflow = true;
            }
        }
        return overflow;
    }
    public static string LimitStringByUTF8(string temp, int limit)
    {
        string outputStr = "";
        int count = 0;

        for (int i = 0; i < temp.Length; i++)
        {
            string tempStr = temp.Substring(i, 1);
            int byteCount = System.Text.ASCIIEncoding.UTF8.GetByteCount(tempStr);
            if (byteCount > 1)
            {
                count += 2;
            }
            else
            {
                count += 1;
            }
            //限制输入字符长度小于对于20个中文长度
            if (count <= limit)
            {
                outputStr += tempStr;
            }
            else
            {
                break;
            }
        }
        return outputStr;
    }
上一篇 下一篇

猜你喜欢

热点阅读