博客已迁到“金陵小周的技术博客”,博客园不在更新发表......

C# 截取字符串方法(包含中英混合)

 1 private string GetByteString(string center, int maxlen, string endStr)
 2         {
 3             string temp = center.Substring(0, (center.Length < maxlen + 1) ? center.Length : maxlen + 1);
 4             byte[] encodedBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(temp);
 5             string outputStr = "";
 6             int count = 0;
 7             for (int i = 0; i < temp.Length; i++)
 8             {
 9                 if ((int)encodedBytes[i] == 63)
10                     count += 2;
11                 else
12                     count += 1;
13 
14                 if (count <= maxlen - endStr.Length)
15                     outputStr += temp.Substring(i, 1);
16                 else if (count > maxlen)
17                     break;
18             }
19             if (count <= maxlen)
20             {
21                 outputStr = temp;
22                 endStr = "";
23             }
24             outputStr += endStr;
25             return outputStr;
26         }

 

posted @ 2015-11-02 10:01  Pete-Jones  阅读(495)  评论(0编辑  收藏  举报

博客已迁到“金陵小周的技术博客”,博客园不在更新发表......