C#字符串截取

 1 #region 截取指定字节长度的字符串
 2         /// <summary>
 3         /// 截取指定字节长度的字符串
 4         /// </summary>
 5         /// <param name="str">原字符串</param>
 6         /// <param name="len">截取字节长度</param>
 7         /// <returns></returns>
 8         public static string CutByteString(string str, int len)
 9         {
10             string result = string.Empty;// 最终返回的结果
11             if (string.IsNullOrEmpty(str)) { return result; }
12             int byteLen = System.Text.Encoding.Default.GetByteCount(str);// 单字节字符长度
13             int charLen = str.Length;// 把字符平等对待时的字符串长度
14             int byteCount = 0;// 记录读取进度
15             int pos = 0;// 记录截取位置
16             if (byteLen > len)
17             {
18                 for (int i = 0; i < charLen; i++)
19                 {
20                     if (Convert.ToInt32(str.ToCharArray()[i]) > 255)// 按中文字符计算加2
21                     { byteCount += 2; }
22                     else// 按英文字符计算加1
23                     { byteCount += 1; }
24                     if (byteCount > len)// 超出时只记下上一个有效位置
25                     {
26                         pos = i;
27                         break;
28                     }
29                     else if (byteCount == len)// 记下当前位置
30                     {
31                         pos = i + 1;
32                         break;
33                     }
34                 }
35                 if (pos >= 0)
36                 { result = str.Substring(0, pos); }
37             }
38             else
39             { result = str; }
40             return result;
41         }
42         #endregion
posted @ 2012-04-13 10:32  txsun  阅读(549)  评论(0编辑  收藏  举报