C# Truncate String Text


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.