/// <summary>
/// Truncate a string at the end, vice the middle, of a word.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="length">The maximum length of the returned string.</param>
/// <param name="addEllipsis">Specifies whether an ellipsis (...) is added to the end of the string.</param>
/// <returns>A substring of the original, truncated at the end of a word.</returns>
/// <remarks>
/// This is primarily a truncate function with the ability to not leave partial words in the result.
/// The input string is returned if it is null, is less than the truncation length, or the truncation length
/// is zero or negative. Added ellipsis reduces the returned string length by at least three characters.
/// </remarks>
public static String TruncateAtWord(this String input, int length, bool addEllipsis)
{
// Return unchanged if no truncation required
if ((input == null) || (input.Length <= length) || (length <= 0))
{
return input;
}
// Ensure length meets conditions
if (addEllipsis && (length > 3))
{
length -= 3;
}
else
{
addEllipsis = false;
}
// Truncate based on passed length
String work = input.Substring(0, length);
// Return if truncation was at the end of a word
if (input.Substring(length, 1) == " ")
{
// Optionally add ellipsis
return (addEllipsis ? (work + "...") : work);
}
// Truncate again before last space in string, if any
int lengthToSpace = work.LastIndexOf(" ");
if (lengthToSpace > 0)
{
work = work.Substring(0, lengthToSpace);
}
// Optionally add ellipsis
return (addEllipsis ? (work + "...") : work);
}