C#截取字符串

时间:2014-04-30 23:51:33   收藏:0   阅读:441
bubuko.com,布布扣
    public class SubStrHelper
    {
        /// <summary>
        /// 截取字符串长度,中文二字节
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length">字节长度</param>
        /// <returns></returns>
        public static string GetSubString(string str, int byteLength, string moreTag = "...")
        {
            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]+"))            //匹配中文
                if (Regex.IsMatch(temp.Substring(i, 1), @"[^\x00-\xff]+"))                  //匹配双字节字符(包括中文)
                {
                    j += 2;
                }
                else
                {
                    j += 1;
                }
                if (j <= byteLength)
                {
                    k += 1;
                }
                if (j > byteLength)
                {
                    return string.Format("{0}{1}", temp.Substring(0, k), moreTag);
                }
            }
            return temp;
        }
    }
bubuko.com,布布扣

 

C#截取字符串,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!