当前位置:asp编程网>技术教程>Net教程>  正文

C#截取字符串函数:汉字算两个,数字算一个

2011-12-23 13:25:04   来源:www.aspbc.com    作者:wangsdong   浏览量:2863   收藏
        /// <summary>
        /// 截取指定数量字符中英混排
        /// </summary>
        /// <param name="str">要截取的字符串变量</param>
        /// <param name="length">要截取的长度</param>
        /// <param name="flag">flag=false表示不需要加省略号</param>
        /// <param name="author">wangsdong</param>
        /// <param name="from">www.aspbc.com</param>
        /// <returns></returns>
        public static string GetSubString(string str, int length, bool flag)
        {
            string temp = str;
            int j = 0;
            int k = 0;
            for (int i = 0; i < temp.Length; i++)
            {
                if (Regex.IsMatch(temp.Substring(i, 1), @"[\u4e00-\u9fa5]+"))
                {
                    j += 2;
                }
                else
                {
                    j += 1;
                }
                if (j <= length)
                {
                    k += 1;
                }
                if (j >= length)
                {
                    temp = temp.Substring(0, k);
                    break;
                }
            }
            if (flag)
            {
                temp += "...";
            }
            return temp;
        }

关于我们-广告合作-联系我们-积分规则-网站地图

Copyright(C)2013-2017版权所属asp编程网