c#完美截断字符串(中文+非中文)

public static string Truncation(this HtmlHelper htmlHelper, string str, int len)
        {
            if (str == null || str.Length == 0 || len <= 0)
            {
                return string.Empty;
            }

            int l = str.Length;

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

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

  

posted @ 2012-06-07 12:59  火拳阿飞  阅读(506)  评论(0编辑  收藏  举报