Posted By

corydeppen on 06/28/10


Tagged

String c extension-method


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

Tyster


Chop words


 / Published in: C#
 

URL: http://www.mikesdotnetting.com/Article/137/Displaying-The-First-n-Characters-Of-Text

Returns part of a string up to the specified number of characters, while maintaining full words.

  1. /// <summary>
  2. /// Returns part of a string up to the specified number of characters, while maintaining full words
  3. /// <para>http://www.mikesdotnetting.com/Article/137/Displaying-The-First-n-Characters-Of-Text</para>
  4. /// </summary>
  5. /// <param name="s"></param>
  6. /// <param name="length">Maximum characters to be returned</param>
  7. /// <returns>String</returns>
  8. public static string Chop(this string s, int length)
  9. {
  10. if (String.IsNullOrEmpty(s))
  11. {
  12. throw new ArgumentNullException(s);
  13. }
  14. var words = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  15. var sb = new StringBuilder();
  16.  
  17. foreach (var word in words.Where(word => (sb.ToString().Length + word.Length) <= length))
  18. {
  19. sb.Append(word + " ");
  20. }
  21. return sb.ToString().TrimEnd(' ') + "...";
  22. }

Report this snippet  

You need to login to post a comment.