获取包含中文字符串的长度、截取包含中文的字符串

        /// <summary>
        /// 截取包含中文、英文、中英文混合字符的字符串
        /// </summary>
        /// <param name="s"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static String Substring(this string s, int length)
        {
            if (s.GetLength() > length)
            {
                if (s == null || s.Length == 0 || length <= 0)
                {
                    return string.Empty;
                }

                int l = s.Length;

                #region 计算长度
                int clen = 0;
                while (clen < length && clen < l)
                {
                    //每遇到一个中文,则将目标长度减一。
                    if ((int)s[clen] > 128) { length--; }
                    clen++;
                }
                #endregion

                if (clen < l)
                {
                    return s.Substring(0, clen) + "...";
                }
                else
                {
                    return s;
                }
            }
            else
            {
                return s;
            }
        }

        /// <summary>
        /// 获取中文、英文、中英文混合字符串长度
        /// </summary>
        /// <param name="strSource"></param>
        /// <returns></returns>
        public static int GetLength(this string strSource)
        {
            return Encoding.GetEncoding("GB18030").GetBytes(strSource).Length;
        }
posted @ 2012-04-28 17:16  [曾恩]  阅读(467)  评论(0编辑  收藏  举报