欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-12-28 21:09:21
/// /// 按不同的字节编码,通过字节数去截取字符串 /// 数据库UTF-8 1个数字、字母、英文符号算1个长度 1个中文、中文符号算3个长度 /// /// 需截取的字符串 /// 需截取的字节长度 /// 截取的字节编码类型 /// ... ......

 

        /// <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);