Posted By

jasonseney on 10/02/09


Tagged

String c truncate


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

khouser
Priestd09


C# Truncate String Text


 / Published in: C#
 

  1. public static string Truncate(string sourceText, string ellipsis, int min, int max)
  2. {
  3. //If text is shorter than preview length
  4. if (sourceText.Length <= max)
  5. {
  6. return sourceText; //@RETURN break out early if too short
  7. }
  8.  
  9. //Grab the char at the last position allowed
  10. char cutOffChar = sourceText[max];
  11.  
  12. int lastPosition = max;
  13.  
  14. //While the last char isn't a space, cut back until we hit a space or minimum
  15. while (cutOffChar != ' ' && lastPosition > min)
  16. {
  17. lastPosition--;
  18. cutOffChar = sourceText[lastPosition];
  19. }
  20.  
  21. //Crop text and add some dots
  22. string outText = sourceText.Substring(0, lastPosition);
  23. outText += ellipsis;
  24.  
  25. return outText;
  26. }

Report this snippet  

You need to login to post a comment.