貌似比较难写,我也坐沙发等答案,呵呵
/// <summary>
/// 将指定的字符截取指定的长度
/// </summary>
/// <param name="s">要截取的字符串.</param>
/// <param name="length">要截取的长度.</param>
/// <param name="filterHtml">是否过滤html标签.</param>
/// <param name="endWithPoints">是否以省略号结尾.</param>
/// <param name="trim">是否去除左右两端的空白字符(过滤完html标签之后)</param>
/// <returns>string.</returns>
public static string BreakString(string s, int length, bool filterHtml, bool endWithPoints, bool trim) {
if (string.IsNullOrEmpty(s)) {
return s;
}
if (filterHtml) {
s = Regex.Replace(s, @"<\/*[^<>]*>", "");
}
if (trim) {
s = s.Trim();
}
StringBuilder result = new StringBuilder();
for (int x = 0, len = 0; x < s.Length; x++) {
if (Convert.ToInt32(Convert.ToChar(s.Substring(x, 1))) > 255) {
len += 2;
}
else {
len++;
}
if (len > length) {
if (endWithPoints) {
result.Append("...");
}
break;
}
result.Append(s.Substring(x, 1));
}
return result.ToString();
}
遇到过,碰到那种图片性的文章更麻烦,一直没解决