取字符中的长度,考虑单字节和双字节情况

 // 取字符中的长度,考虑单字节和双字节情况
    /// <summary>  
    /// 计算文本长度,区分中英文字符,中文算两个长度,英文算一个长度
    ///
    /// </summary>
    /// <param name="Text">需计算长度的字符串</param>
    /// <returns>int</returns>


    public static string getLength(string Text, int Lenght)
    {
        int len = 0;
        System.Text.Encoding enc = System.Text.Encoding.GetEncoding("Gb2312");
        byte[] bytes = enc.GetBytes(Text);

        for (int i = 0; i < Text.Length; i++)
        {
            byte[] byte_len = enc.GetBytes(Text.Substring(i, 1));
            if (byte_len.Length > 1)
                len += 2;  //如果长度大于1,是中文,占两个字节,+2
            else
                len += 1;  //如果长度等于1,是英文,占一个字节,+1
        }

        Lenght = Lenght * 2 > len ? len : Lenght * 2;

        return enc.GetString(bytes, 0, Lenght-1);


    }

posted on 2006-08-29 10:54  Leetle  阅读(458)  评论(0编辑  收藏  举报

导航