日期:2011-05-03  浏览次数:20399 次

public static string GetFirstString(string stringToSub, int length)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut=false;
            for(int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

                if (nLength > length)
                {
                    isCut=true;
                    break;
                }
            }
            if(isCut)
                return sb.ToString()+"..";
            else
                return sb.ToString();
        }

我是从网上找的方法,然后添加了,如果是超过长度,则在后面添加".."字符。

这在做网站时,显示新闻标题最非常有用,为了保持页面的格局,对标题进行限定长度,这就需要对中文进行双字符计算。