Posted By

krisdb on 12/03/08


Tagged

c-sharp


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

leonbda
umang_nine
khouser


Trim/Truncate


 / Published in: C#
 

  1. private string TrimLength(string text, int length)
  2. {
  3. string output = text;
  4.  
  5. if (text.Length > length)
  6. output = text.Substring(0, length - 1) + "...";
  7.  
  8. return output;
  9. }
  10.  
  11. private string TruncateWords(string text, int wordCount)
  12. {
  13. string output = String.Empty;
  14.  
  15. if (text.Length > 0)
  16. {
  17. try
  18. {
  19. string[] words = text.Split(' ');
  20.  
  21. if (words.Length < wordCount)
  22. wordCount = words.Length;
  23.  
  24. for (int x = 0; x <= wordCount; x++)
  25. output += words[x] + " ";
  26.  
  27. if (words.Length > wordCount)
  28. output = output.Trim() + "...";
  29. }
  30.  
  31. catch { /* do nothing */ }
  32. }
  33.  
  34. return output;
  35. }

Report this snippet  

You need to login to post a comment.