This kind of truncation is always needed if you are displaying a truncated version of a meaningful string in the UI. Rather than simply truncating the list to a specific maximum length it is always handy to chop it to the last meaningful word.
The following lines of code accomplish that task

public static string TruncateToLastWord(string value, int maxLength)
{
string stringToTruncate = value.Substring(0, maxLength);
int indexOfLastSpace = stringToTruncate.LastIndexOf(' ');
string truncatedString = stringToTruncate.Substring(0, indexOfLastSpace);
return string.Format("{0}...", truncatedString);
}

0 comments:

Post a Comment