有可能是没有必要涉及的东西这个简单的正则表达式.采取这种扩展方法:
public static string Abbreviate(this string text, int length) {
if (text.Length <= length) {
return text;
}
char[] delimiters = new char[] { ' ', '.', ',', ':', ';' };
int index = text.LastIndexOfAny(delimiters, length - 3);
if (index > (length / 2)) {
return text.Substring(0, index) + "...";
}
else {
return text.Substring(0, length - 3) + "...";
}
}
Run Code Online (Sandbox Code Playgroud)
如果字符串足够短,则按原样返回.否则,如果在字符串的后半部分中找到"单词边界",则在该点处"优雅地"切断.如果没有,它会在刚好低于所需长度的情况下切断.
如果字符串完全被删除,则会在其上附加省略号("...").
如果您希望字符串包含非自然语言结构(例如URL),则需要对其进行调整以确保在所有情况下都有良好的行为.在这种情况下,使用正则表达式可能会更好.