Asp.net网页中实现截取等宽长度中英文字符串
/// <summary> /// 截取等宽中英文字符串 /// </summary> /// <param name="str">要截取的字符串</param> /// <param name="length">要截取的中文字符长度</param> /// <param name="appendStr">截取后后追加的字符串</param> /// <returns>截取后的字符串</returns> public static string CutStr(object str, int length, string appendStr) { if (str == null) return string.Empty; int len = length * 2; //aequilateLength为中英文等宽长度,cutLength为要截取的字符串长度 int aequilateLength = 0, cutLength = 0; Encoding encoding = Encoding.GetEncoding("gb2312"); string cutStr = str.ToString(); int strLength = cutStr.Length; byte[] bytes; for (int i = 0; i < strLength; i++) { bytes = encoding.GetBytes(cutStr.Substring(i, 1)); if (bytes.Length == 2)//不是英文 aequilateLength += 2; else aequilateLength++; if (aequilateLength <= len) cutLength += 1; if (aequilateLength > len) return cutStr.Substring(0, cutLength) + appendStr; } return cutStr; }
网页中要实现中英文长度一致,还需要设置等宽字体,不然截取的宽度也不准确.
body
{
font-size: 9pt;
font-family:'宋体','新宋体'; /*等宽字体*/
}