c# 实现截取等宽长度中英文字符串
/// <summary>
/// 截取指定长度中英文字符串(宽度一样)
/// </summary>
/// <param name="str">要截取的字符串</param>
/// <param name="length">截取长度,中文字符长度</param>
/// <returns>截取后的字符串</returns>
public static string CutStr(string str, int length)
{
if (str == null)
return string.Empty;
int len = length * 2;
int j = 0, k = 0;
Encoding encoding = Encoding.GetEncoding("gb2312");
for (int i = 0; i < str.Length; i++)
{
byte[] bytes = encoding.GetBytes(str.Substring(i, 1));
if (bytes.Length == 2)//不是英文
j += 2;
else
j++;
if (j <= len)
k += 1;
if (j >= len)
return str.Substring(0, k) + "...";
}
return str;
}
网页中要实现中英文长度一致,还需要设置等宽字体,不然截取的宽度也不准确.
body
{
font-size: 9pt;
font-family:'宋体','新宋体'; /*等宽字体*/
line-height: 1.8em;
}一直用 没整理 上文转至:http://www.cnblogs.com/slyzly/articles/2497676.html