/ Published in: C#
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/// <summary> /// String extension methods. /// </summary> public static class StringExtension { private const string ellipsis = "..."; /// <summary> /// Truncates the supplied content to the max length on a word boundary and adds an ellipsis if longer. /// </summary> /// <param name="content">The string to truncate</param> /// <param name="maxLength">Max number of characters to show, not including continuation content</param> /// <returns>The truncated string</returns> public static string TruncateOnWordBoundary(this string content, int maxLength) { return content.TruncateOnWordBoundary(maxLength, ellipsis); } /// <summary> /// Truncates the supplied content to the max length on a word boundary and adds the suffix if longer. /// </summary> /// <param name="content">The string to truncate</param> /// <param name="maxLength">Max number of characters to show, not including the suffix</param> /// <param name="suffix">Suffix to append if content is truncated</param> /// <returns>The truncated string</returns> public static string TruncateOnWordBoundary(this string content, int maxLength, string suffix) { // No content? Return an empty string. if (String.IsNullOrEmpty(content)) return String.Empty; // Content is shorter than the max length? Return the whole string. if (content.Length < maxLength) return content; // Find the word boundary. int i = maxLength; while (i > 0) { if (Char.IsWhiteSpace(content[i])) break; i--; } // Can't truncate on a word boundary? Just return the suffix, e.g. "...". if (i <= 0) return (suffix ?? ellipsis); // Just in case a null suffix was supplied. return content.Substring(0, i) + (suffix ?? ellipsis); } }