Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- private static Regex _multipleSpacesRegex = new Regex(@" {2,}");
- private static Regex _multipleLineBreaksWithParagraphRegex = new Regex(@"\n{3,}");
- private static Regex _multipleLineBreaksRegex = new Regex(@"\n{2,}");
- private static Regex _paragraphIndentRegex = new Regex(@"\n[\s\t]{1,}");
- public static string TruncateByWords(this string source, int wordCount, string countinueString = " ...")
- {
- if (string.IsNullOrWhiteSpace(source))
- return source;
- var array = source.Trim()
- .Split(' ')
- .Where(i => !string.IsNullOrWhiteSpace(i));
- if (array.Count() <= wordCount)
- return array.Take(wordCount).Aggregate((a, i) => a + " " + i);
- return array.Take(wordCount).Aggregate((a, i) => a + " " + i) + countinueString;
- }
- public static string TruncateBySymbols(this string source, int symbolsCount, string countinueString = " ...")
- {
- if (string.IsNullOrEmpty(source))
- return string.Empty;
- var trimmedSource = source.Trim();
- var truncatedSource = trimmedSource.Length <= symbolsCount ? trimmedSource : source.Substring(0, symbolsCount).Trim();
- if (truncatedSource.Length < trimmedSource.Length)
- truncatedSource += countinueString;
- return truncatedSource;
- }
- public static string ClearMultipleLineBreaks(this string self, bool allowParagraphs = true)
- {
- return self.RegexReplace(allowParagraphs
- ? _multipleLineBreaksWithParagraphRegex
- : _multipleLineBreaksRegex, "\n"); ;
- }
- public static string ClearParagraphIndents(this string self)
- {
- return self.RegexReplace(_paragraphIndentRegex, "\n"); ;
- }
Add Comment
Please, Sign In to add comment