两种按字节载取字符串的方法

 protected string  GetTitle(string title)
    {
   
        string title1 = "";
       //按字节获取字符串的长度  
      int len =  System.Text.Encoding.Default.GetByteCount(title);
        if (len > 20)
        {
            title1 = GetByteSubString(title, 18) + "...";
        }
        else
        {
            title1 = title;
        }
        return title1 ;
    }
    public static string GetString(string str, int length)
    {
        int i = 0, j = 0;
        foreach (char chr in str)
        {
            if ((int)chr > 127)
            {
                i += 2;
            }
            else
            {
                i++;
            }
            if (i > length)
            {
                str = str.Substring(0, j) + "...";
                break;
            }
            j++;
        }
        return str;

    }

    private static string GetByteSubString(string content, int length)
    {
        Encoding encoding = Encoding.GetEncoding("gb2312");
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[length];
        bytes = encoding.GetBytes(content);
        if (length % 2 == 0)
        {
            sb.Append(encoding.GetString(bytes, 0, length));
        }
        else
        {
            sb.Append(encoding.GetString(bytes, 0, length - 1));
            sb.Append("..");
        }
        return sb.ToString();
    }

posted @ 2008-06-27 16:04  海皮球  阅读(292)  评论(0编辑  收藏  举报