码迷,mamicode.com
首页 > 其他好文 > 详细

Encoding encoding = Encoding.GetEncoding("gb2312"); 与byte[] ping = Encoding.UTF8.GetBytes(inputString);区别

时间:2015-07-23 17:09:37      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

 Encoding encoding = Encoding.GetEncoding("gb2312"); 与byte[] ping = Encoding.UTF8.GetBytes(inputString);区别

 public static string SubString(string inputString, int length)
        {
            byte[] ping = Encoding.UTF8.GetBytes(inputString);
            int count=Encoding.UTF8.GetByteCount(inputString);
            if (count <= length * 2)
            {
                return inputString;
            }
            ASCIIEncoding ascii = new ASCIIEncoding();
            int tempLen = 0;
            string tempString = "";
            byte[] s = ascii.GetBytes(inputString);
            for (int i = 0; i < s.Length; i++)
            {
                if ((int)s[i] == 63)
                {
                    tempLen += 2;
                }
                else
                {
                    tempLen += 1;
                }
                tempString += inputString.Substring(i, 1);
                if (tempLen >= length * 2)
                    break;
            }
            return tempString;
        }

 

 public static string GetSub(string sub, int length)         {             if (sub == null) return string.Empty;             int len = length * 2;             //aequilateLength为中英文等宽长度,cutLength为要截取的字符串长度             int aequilateLength = 0, cutLength = 0;             Encoding encoding = Encoding.GetEncoding("gb2312");

            string cutStr = sub.ToString();             int strLength = cutStr.Length;             byte[] bytes;             for (int i = 0; i < strLength; i++)             {                 bytes = encoding.GetBytes(cutStr.Substring(i, 1));                 if (bytes.Length == 2)//不是英文                     aequilateLength += 2;                 else                     aequilateLength++;

                if (aequilateLength <= len) cutLength += 1;

                if (aequilateLength > len)                     return cutStr.Substring(0, cutLength);//+ "..."             }             return cutStr;         }

Encoding encoding = Encoding.GetEncoding("gb2312"); 与byte[] ping = Encoding.UTF8.GetBytes(inputString);区别

标签:

原文地址:http://www.cnblogs.com/DTWolf/p/4670697.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!