C# 按不同的字节编码,通过字节数去截取字符串

时间:2021-11-22 10:47:31

 

        /// <summary>
        /// 按不同的字节编码,通过字节数去截取字符串
        /// 数据库UTF-8 1个数字、字母、英文符号算1个长度 1个中文、中文符号算3个长度
        /// </summary>
        /// <param name="origStr">需截取的字符串</param>
        /// <param name="bytesLength">需截取的字节长度</param>
        /// <param name="dstEncoding">截取的字节编码类型</param>
        /// <returns></returns>
        public static string GetSubString(string origStr, int bytesLength, Encoding dstEncoding)
        {
            if (origStr == null || origStr.Length == 0 || bytesLength < 0)
                return "";
            int bytesCount = dstEncoding.GetByteCount(origStr);
            if (bytesCount > bytesLength)
            {
                int readyLength = 0;
                int byteLength;
                for (int i = 0; i < origStr.Length; i++)
                {
                    byteLength = dstEncoding.GetByteCount(new char[] { origStr[i] });
                    readyLength += byteLength;
                    if (readyLength == bytesLength)
                    {
                        origStr = origStr.Substring(0, i + 1);// + "..."; 加省略号
                        break;
                    }
                    else if (readyLength > bytesLength)
                    {
                        origStr = origStr.Substring(0, i);// + "..."; 加省略号
                        break;
                    }
                }
            }
            return origStr;
        }

 

sting newStr = GetSubString(origStr, bytesLength, Encoding.UTF8);