高效中英文字符串截取方法[不用普遍的正则表达式方法]

原文发布时间为:2009-04-14 —— 来源于本人的百度文章 [由搬家工具导入]

C# code
public static string Intercept(string input, int p) { Encoding encode = Encoding.GetEncoding("gb2312"); byte[] byteArr = encode.GetBytes(input); if (byteArr.Length <= p) return input; int m = 0, n = 0; foreach (byte b in byteArr) { if (n >= p) break; if (b > 127) m++; //重要一步:对前p个字节中的值大于127的字符进行统计 n++; } if (m % 2 != 0) n = p + 1; //如果非偶:则说明末尾为双字节字符,截取位数加1 return encode.GetString(byteArr, 0, n); }


测试代码:
C# code
Console.WriteLine(Intercept("ABC中国人", 7)); Console.WriteLine(Intercept("ABCD中国人", 7)); Console.WriteLine(Intercept("ABC中D国人", 7));

原文地址:https://www.cnblogs.com/handboy/p/7153304.html