截取字符串

 1  /// <summary>
 2         /// 截取指定长度字符串
 3         /// </summary>
 4         /// <param name="inputString">要处理的字符串</param>
 5         /// <param name="len">指定长度</param>
 6         /// <returns>返回处理后的字符串</returns>
 7         public static string ClipString(string inputString, int len)
 8         {
 9             bool isShowFix = false;
10             if (len % 2 == 1)
11             {
12                 isShowFix = true;
13                 len--;
14             }
15             System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
16             int tempLen = 0;
17             string tempString = "";
18             byte[] s = ascii.GetBytes(inputString);
19             for (int i = 0; i < s.Length; i++)
20             {
21                 if ((int)s[i] == 63)
22                     tempLen += 2;
23                 else
24                     tempLen += 1;
25 
26                 try
27                 {
28                     tempString += inputString.Substring(i, 1);
29                 }
30                 catch
31                 {
32                     break;
33                 }
34 
35                 if (tempLen > len)
36                     break;
37             }
38 
39             byte[] mybyte = System.Text.Encoding.Default.GetBytes(inputString);
40             if (isShowFix && mybyte.Length > len)
41                 tempString += "";
42             return tempString;
43         }

 

posted @ 2014-02-25 09:22  张三的编码生活  阅读(164)  评论(0编辑  收藏  举报