惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
D
Docker
月光博客
月光博客
MongoDB | Blog
MongoDB | Blog
Vercel News
Vercel News
美团技术团队
博客园 - 叶小钗
I
InfoQ
Jina AI
Jina AI
博客园 - 司徒正美
雷峰网
雷峰网
B
Blog
Y
Y Combinator Blog
A
About on SuperTechFans
WordPress大学
WordPress大学
酷 壳 – CoolShell
酷 壳 – CoolShell
大猫的无限游戏
大猫的无限游戏
Microsoft Security Blog
Microsoft Security Blog
Stack Overflow Blog
Stack Overflow Blog
腾讯CDC
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recent Announcements
Recent Announcements
V
V2EX
N
Netflix TechBlog - Medium

博客园 - 大牛博客

广东早茶的悠闲时光 用户中心 - 博客园 GridView数据绑定控件和ObjectDataSource数据源控件实现排序功能 - 大牛博客 - 博客园 asp.net 常用字符串过滤方法 非常实用的Asp.net常用的51个代码 - 大牛博客 - 博客园 JS 中面向对象的5钟写法 GridView的RowCommand事件中取得行索引 - 大牛博客 - 博客园 .netframework3.5 中TimeZoneInfo 类的使用 GridView,DataList,Repeater,DetailsView的遍历行代码 - 大牛博客 - 博客园 ASP.NET 2.0上传图片生成缩略图类 合理选择贪婪模式与非贪婪模式 - 大牛博客 - 博客园 揭开正则表达式的神秘面纱 asp.net下载文件 - 大牛博客 - 博客园 C#数据结构之双向链表 C#数据结构之队列 ASP.NET四种页面导航方式之比较与选择 asp.net页面事件执行顺序 ASP.NET纯数字验证码 SQL 2005 ROW_NUMBER() 语句分页 | SQL效率最高的分页查询数据
中英文字符串截取方法 - 大牛博客 - 博客园
大牛博客 · 2009-06-21 · via 博客园 - 大牛博客

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国