Mega Code Archive

 
Categories / C# / Data Types
 

Truncate On Word Boundary

/*    Open Intel     Copyright Â© 2011 â€“ ISC. All Rights Reserved. */ using System; using System.Text; using System.Text.RegularExpressions; using System.Windows.Media; namespace OI.Framework {     public static class Utility     {         public static string TruncateOnWordBoundary(this string str, int maxChars)         {             if (!string.IsNullOrEmpty(str))             {                 char[] chars = { ' ' };                 string[] words = str.Split(chars, StringSplitOptions.RemoveEmptyEntries);                 var sb = new StringBuilder();                 int count = 0;                 foreach (var word in words)                 {                     count += (word.Length + 1);                     if (count > maxChars)                     {                         sb.Append("...");                         break;                     }                     sb.Append(word + ' ');                 }                 return sb.ToString();             }             return "";         }     } }