高效中英文字符串截取方法(转)

 

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);
        }

 

 测试代码:

 

Console.WriteLine(Intercept("ABC中国人"7));
Console.WriteLine(Intercept(
"ABCD中国人"7));
Console.WriteLine(Intercept(
"ABC中D国人"7));

 

 

 

posted @ 2009-04-09 14:48  瞭望者  阅读(228)  评论(0)    收藏  举报