Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static string FixExtraSpaces(this string s)
- {
- if (string.IsNullOrEmpty(s))
- {
- return s;
- }
- const char whiteSpace = ' ';
- var k = -1;
- for (var i = s.Length - 1; i >= 0; i--)
- {
- var ch = s[i];
- if (k < 2)
- {
- if (ch == whiteSpace)
- {
- k = i + 1;
- }
- }
- else if (ch != whiteSpace)
- {
- // only keep white space if it doesn't succeed/precede CRLF
- // 2: when we `if (k - (i + skipCount) >= 1) = > 0`
- var skipCount = (ch == '\n' || ch == '\r') || (k < s.Length && (s[k] == '\n' || s[k] == '\r')) ? 1 : 2;
- // extra space found
- if (k - (i + skipCount) >= 1)
- {
- s = s.Remove(i + 1, k - (i + skipCount));
- }
- // Reset remove length.
- k = -1;
- }
- }
- return s;
- }
- Note: there is a note that explain why we return 2!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement