zoukankan      html  css  js  c++  java
  • 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/

  • 相关阅读:
    Java web学习总结
    java web知识点
    SSH进阶之路
    file /etc/httpd/conf.d/php.conf from install of php-5.6.37-1.el7.remi.x86_64 conflicts with file from package mod_php71w-7.1.18-1.w7.x86_64
    centos7上安装php5.6
    centos7 删除php
    centos7删除yum安装的php
    给服务器加内存
    Hyperledger Fabric 开发环境搭建 centos7系统
    79
  • 原文地址:https://www.cnblogs.com/lgzslf/p/2375120.html
Copyright © 2011-2022 走看看