circlesport

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
/// <summary>
    /// 截获定长的字符串
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="length">需要截获的长度</param>
    /// <returns>截获后的字符串</returns>
    static public string FixLenth ( string source, int length)
    {
      return FixLenth ( source, length, "...");
    }
    /// <summary>
    /// 截获定长的字符串
    /// </summary>
    /// <param name="source">源字符串</param>
    /// <param name="length">需要截获的长度</param>
    /// <param name="postfix">如果字符串被截短,需要添加什么样的后缀</param>
    /// <returns>截获后的字符串</returns>
    static public string FixLenth ( string source, int length, string postfix)
    {
      if ( source == null )
        throw new ArgumentNullException( "source" );
      if ( postfix == null )
        postfix = "...";

      if ( length < postfix.Length )
        throw new ArgumentOutOfRangeException( "length" );
        

      int postfixLength = System.Text.Encoding.GetEncoding("GB2312").GetByteCount( postfix);
      int srcLength = System.Text.Encoding.GetEncoding("GB2312").GetByteCount( source);

      if ( srcLength > length)
      {
        for ( int i = source.Length; i>0; i--)
        {
          srcLength = System.Text.Encoding.GetEncoding("GB2312").GetByteCount( source.Substring(0,i) );

          if ( srcLength <= length - postfixLength)
            return source.Substring(0,i) + postfix;
        }
        return "";
      }
      else
        return source;
    }


--------------------------------------------------------

能给个思路吗?
我想知道是怎么做的

--------------------------------------------------------

GB2312编码会将一个中文字编码成两个字节,而英文字母只会编码成一个字节,那么根据编码后的字节数就能知道是否满足截断的要求了。那么,弄个循环不断的缩短截断长度直到满足要求为止就行了。

--------------------------------------------------------

就像这样
int postfixLength = System.Text.Encoding.GetEncoding("GB2312").GetByteCount( postfix);
      int srcLength = System.Text.Encoding.GetEncoding("GB2312").GetByteCount( source);
posted on 2007-07-02 15:33  无极.net  阅读(454)  评论(1编辑  收藏  举报