C#: Shorten text to a fixed length

October 05, 2010 C# Snippet
Here's a little snippet of code to help shorten text to fit inside a predefined length. It doesn't just cut a position X, it's try to find where the closest white space or stop character and instead cut there. However, if the character to cut at is found below half the length of the defined length it's ignored.

Call by:
string shortAndSweet = LimitCharacters(aReallyLongText, 100);

Function:
public string LimitCharacters(string text, int length) {
// 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) + "...";
}
}
Adjust the delimiters as you find aproperiate.

Related posts: