截取字符串长度

    public static string SubString(string inputString, int length)
       {
           if (Encoding.UTF8.GetByteCount(inputString) <= 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 - 1) * 2) break;
           }
           //如果截过则加上半个省略号    
           if (System.Text.Encoding.Default.GetBytes(inputString).Length > length)
               tempString += "...";
           return tempString;
       }
posted @ 2011-04-29 11:16  tangself  阅读(234)  评论(0编辑  收藏  举报