C#: Limit number of characters in text to a certain length

Sometimes just cutting a too long string will do the job, but sometimes you might want a more content aware cut.

This little snippet takes two parameters: the text to (if too long) truncate and the required max length. If the text is within the max length nothing is done, the text is returned as is. Otherwise the code will try to break at the last stop character or after last word (depending on how the sentence is structured).
public static string LimitCharacters(string text, int length) {
if(string.IsNullOrEmpty(text)) {
return string.Empty;
}

// If text in shorter or equal to length, just return it
if (text.Length <= length) {
return text;
}

// Text is longer, so try to find out where to cut
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) + "...";
}
}

Related posts:

Comments

comments powered by Disqus