.net 计算文本长度

来源:互联网 发布:阿里云服务器租用费用 编辑:程序博客网 时间:2024/05/22 10:50
 /// <summary>        /// 计算文本长度,区分中英文字符,中文算两个长度,英文算一个长度        /// </summary>        /// <param name="str"></param>        /// <param name="length"></param>        /// <returns></returns>        public static int TextLength(string strText)        {            int intLen = 0;            if (!String.IsNullOrEmpty(strText))            {                for (int i = 0; i < strText.Length; i++)                {                    byte[] bytelen = Encoding.Default.GetBytes(strText.Substring(i, 1));                    if (bytelen.Length > 1)                        intLen += 2;  //如果长度大于1,是中文,占两个字节,+2                    else                        intLen += 1;  //如果长度等于1,是英文,占一个字节,+1                }            }            return intLen;        }

原创粉丝点击