C#对字符串执行字节操作

写两个扩展方法,分别现“得到字符串的字长度”和“按字节长度截取字符串”的功能。

public static class Test
    {
        /// <summary>
        /// 按字节长度截取字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="num">要截取的字节个数</param>
        /// <returns></returns>
        public static string SubBytestring(this string str, int num)
        {
            string strNum = str.Trim();
            if (Encoding.Default.GetBytes(strNum).Length <= num)
            {
                return strNum;
            }
            byte[] bytes2 = Encoding.Default.GetBytes(str.Substring(0,str.Length<num?str.Length:num));
            string strNum1 = Encoding.Default.GetString(bytes2, 0, num);
            int len = strNum1.Length;
            if (str.Substring(0, len) != strNum1)
            {
                return Encoding.Default.GetString(bytes2, 0, num - 1);
            }
            return strNum1;
        }
        /// <summary>
        /// 得到字符串的字节长度
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int ByteLength(this string str)
        {
          return  Encoding.Default.GetBytes(str.Trim()).Length;
        }
    }

 

调用:

  string str = "a中b华3".SubBytestring(6);
  int len = "a中b华3".ByteLength();

 

参考:http://yandavid.blog.163.com/blog/static/10779084201010182383338/

 

posted @ 2012-03-01 10:29  男儿当自强IT  阅读(718)  评论(0编辑  收藏  举报