[转]C# 截取指定长度的中英文混合字符串的算法

/// <summary>
        /// 截取指定长度的中英文混合字符串的算法 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string GetSubString(string str, int length)
        {
            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++;
                }
                if (j >= length)
                {
                    return temp.Substring(0, k);
                }
            }
            return temp;
        }

posted on 2012-10-03 16:37  YuanSong  阅读(253)  评论(0编辑  收藏  举报

导航