Guest User

Untitled

a guest
Jan 18th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. private static Regex _multipleSpacesRegex = new Regex(@" {2,}");
  2. private static Regex _multipleLineBreaksWithParagraphRegex = new Regex(@"\n{3,}");
  3. private static Regex _multipleLineBreaksRegex = new Regex(@"\n{2,}");
  4. private static Regex _paragraphIndentRegex = new Regex(@"\n[\s\t]{1,}");
  5.  
  6. public static string TruncateByWords(this string source, int wordCount, string countinueString = " ...")
  7. {
  8. if (string.IsNullOrWhiteSpace(source))
  9. return source;
  10.  
  11. var array = source.Trim()
  12. .Split(' ')
  13. .Where(i => !string.IsNullOrWhiteSpace(i));
  14.  
  15. if (array.Count() <= wordCount)
  16. return array.Take(wordCount).Aggregate((a, i) => a + " " + i);
  17.  
  18. return array.Take(wordCount).Aggregate((a, i) => a + " " + i) + countinueString;
  19. }
  20.  
  21. public static string TruncateBySymbols(this string source, int symbolsCount, string countinueString = " ...")
  22. {
  23. if (string.IsNullOrEmpty(source))
  24. return string.Empty;
  25.  
  26. var trimmedSource = source.Trim();
  27. var truncatedSource = trimmedSource.Length <= symbolsCount ? trimmedSource : source.Substring(0, symbolsCount).Trim();
  28.  
  29. if (truncatedSource.Length < trimmedSource.Length)
  30. truncatedSource += countinueString;
  31.  
  32. return truncatedSource;
  33. }
  34.  
  35. public static string ClearMultipleLineBreaks(this string self, bool allowParagraphs = true)
  36. {
  37. return self.RegexReplace(allowParagraphs
  38. ? _multipleLineBreaksWithParagraphRegex
  39. : _multipleLineBreaksRegex, "\n"); ;
  40. }
  41.  
  42. public static string ClearParagraphIndents(this string self)
  43. {
  44. return self.RegexReplace(_paragraphIndentRegex, "\n"); ;
  45. }
Add Comment
Please, Sign In to add comment