zoukankan      html  css  js  c++  java
  • c# 判断字符是否是全角, 获取字符串的字节数 , 获取字符串指定长度字节数的字符串

    1 Encoding.Default.GetByteCount(checkString);  =2 全角 =1 半角

            /// <summary>
            /// 获取字符串的字节长度
            /// </summary>
            /// <param name="str"></param>
            /// <returns></returns>
            public static int GetStringByteLength(this string str)
            {
                 int j = 0;
                foreach (char c in str)
                {
                    string checkString = c + "";
                    j += Encoding.Default.GetByteCount(checkString);
                }
                return j;
         }
            /// <summary>
            /// 根据字节数截取字符串
            /// </summary>
            /// <param name="s">输入的字符串</param>
            /// <param name="length">要截取的字节长度</param>
            /// <returns></returns>
            public static string bSubstring(this string s, int length)
            {
                if (length>=s.GetStringByteLength())
                {
                    return s;
                }
                string outStr="";
                int j = 0;
                foreach (char c in s)
                {
                    string checkString = c + "";
                    j += Encoding.Default.GetByteCount(checkString);
                    outStr += c;
                    if (j>=length) break;
                }
               return outStr;
            }
  • 相关阅读:
    time fly
    小论文初稿终于完成
    leetcode之Length of Last Word
    static关键字
    参数传递
    this关键字
    面向对象有三大特征
    空指针异常
    变量按数据类型分为
    构造方法
  • 原文地址:https://www.cnblogs.com/simadi/p/3918039.html
Copyright © 2011-2022 走看看