首页 > 代码库 > c# 判断字符是否是全角, 获取字符串的字节数 , 获取字符串指定长度字节数的字符串

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;        }