中英文字符串截取方法

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

测试代码的结果: 

ABC中国 
ABCD中国 
ABC中D国
posted @ 2009-06-21 15:07  大牛博客  阅读(404)  评论(0编辑  收藏  举报