TruncateOnWordBoundary - a useful extension method for cutting a string short, but not in the middle of a word.


/ Published in: C#
Save to your folder(s)

Ever wanted a method that can truncate a string, but only on a word boundary? This method works like Substring() but doesn't snip a string in the middle of a word, i.e. it only truncates the string on a word boundary. Useful for producing a summary from long text, or when limiting the length of an input field.


Copy this code and paste it in your HTML
  1. /// <summary>
  2. /// String extension methods.
  3. /// </summary>
  4. public static class StringExtension
  5. {
  6. private const string ellipsis = "...";
  7.  
  8. /// <summary>
  9. /// Truncates the supplied content to the max length on a word boundary and adds an ellipsis if longer.
  10. /// </summary>
  11. /// <param name="content">The string to truncate</param>
  12. /// <param name="maxLength">Max number of characters to show, not including continuation content</param>
  13. /// <returns>The truncated string</returns>
  14. public static string TruncateOnWordBoundary(this string content, int maxLength)
  15. {
  16. return content.TruncateOnWordBoundary(maxLength, ellipsis);
  17. }
  18.  
  19. /// <summary>
  20. /// Truncates the supplied content to the max length on a word boundary and adds the suffix if longer.
  21. /// </summary>
  22. /// <param name="content">The string to truncate</param>
  23. /// <param name="maxLength">Max number of characters to show, not including the suffix</param>
  24. /// <param name="suffix">Suffix to append if content is truncated</param>
  25. /// <returns>The truncated string</returns>
  26. public static string TruncateOnWordBoundary(this string content, int maxLength, string suffix)
  27. {
  28. // No content? Return an empty string.
  29. if (String.IsNullOrEmpty(content))
  30. return String.Empty;
  31.  
  32. // Content is shorter than the max length? Return the whole string.
  33. if (content.Length < maxLength)
  34. return content;
  35.  
  36. // Find the word boundary.
  37. int i = maxLength;
  38. while (i > 0)
  39. {
  40. if (Char.IsWhiteSpace(content[i]))
  41. break;
  42. i--;
  43. }
  44.  
  45. // Can't truncate on a word boundary? Just return the suffix, e.g. "...".
  46. if (i <= 0)
  47. return (suffix ?? ellipsis); // Just in case a null suffix was supplied.
  48.  
  49. return content.Substring(0, i) + (suffix ?? ellipsis);
  50. }
  51. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.