Skip to content

Instantly share code, notes, and snippets.

@iambacon
Created August 14, 2015 10:36
Show Gist options
  • Save iambacon/75e3f1d7a0e0eb8eac2a to your computer and use it in GitHub Desktop.
Save iambacon/75e3f1d7a0e0eb8eac2a to your computer and use it in GitHub Desktop.
/// <summary>
/// truncate string at the last full word before char limit and appends ...
/// </summary>
/// <param name="input">The input.</param>
/// <param name="length">The string length.</param>
/// <returns>The truncated string.</returns>
public static string TruncateAtWord(this string input, int length)
{
if (input == null || input.Length < length)
{
return input;
}
int nextSpace = input.LastIndexOf(" ", length, StringComparison.Ordinal);
return string.Format("{0}...", input.Substring(0, (nextSpace > 0) ? nextSpace : length).Trim());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment