按字节截取中英文

Posted on 2015-01-29 11:20  南一  阅读(228)  评论(0编辑  收藏  举报
 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             while (true)
 6             {
 7                 Console.WriteLine("请输入字符串:");
 8                 string s = getInput(0);
 9                 Console.WriteLine("请输入截取的字节长度(整数):");
10                 int l = Convert.ToInt32(getInput(1));
11                 s = GetSubStringByByte(s, l);
12                 Console.WriteLine("输出的结果:" + s);
13                 Console.WriteLine("................................................\n");
14             }
15         }
16         static string getInput(int type)
17         {
18             while (true)
19             {
20                 string s = string.Empty;
21                 try
22                 {
23                     s = Console.ReadLine();
24                 }
25                 catch { }
26                 if (type == 0)
27                 {
28                     if (!string.IsNullOrWhiteSpace(s))
29                     {
30                         return s;
31                     }
32                     else
33                     {
34                         Console.WriteLine("请输入正确的字符串:");
35                     }
36                 }
37                 else
38                 {
39                     int l = 0;
40                     if (int.TryParse(s,out l))
41                     {
42                         return s;
43                     }
44                     else
45                     {
46                         Console.WriteLine("请输入正确的整数:");
47                     }
48                 }
49             }
50         }
51         /// <summary>
52         /// 按字节截取字符串
53         /// </summary>
54         /// <param name="s">所要截取的字符串</param>
55         /// <param name="l">截取字节长度</param>
56         /// <param name="endStr">后接字符串(如“...”)</param>
57         /// <returns></returns>
58         static public string GetSubStringByByte(string s, int l, string endStr = "")
59         {
60             string temp = s;
61             if (string.IsNullOrEmpty(temp))
62             {
63                 return string.Empty;
64             }
65             else if (Regex.Replace(temp, "[\u4e00-\u9fa5]", "zz", RegexOptions.IgnoreCase).Length <= l)
66             {
67                 return temp;
68             }
69             int j = 0, k = 0;
70 
71             CharEnumerator ce = temp.GetEnumerator();
72             while (ce.MoveNext())
73             {
74                 j += (ce.Current > 0 && ce.Current < 255) ? 1 : 2;
75 
76                 if (j <= l)
77                 {
78                     k++;
79                 }
80                 else
81                 {
82                     temp = s.Substring(0, k);
83                     break;
84                 }
85             }
86             return temp + endStr;
87         }
88     }