Advertisement
ivandrofly

SubtitleEdit: FixExtraSpaces

Aug 27th, 2023
1,302
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.78 KB | None | 0 0
  1. public static string FixExtraSpaces(this string s)
  2. {
  3.     if (string.IsNullOrEmpty(s))
  4.     {
  5.         return s;
  6.     }
  7.  
  8.     const char whiteSpace = ' ';
  9.     var k = -1;
  10.     for (var i = s.Length - 1; i >= 0; i--)
  11.     {
  12.         var ch = s[i];
  13.         if (k < 2)
  14.         {
  15.             if (ch == whiteSpace)
  16.             {
  17.                 k = i + 1;
  18.             }
  19.         }
  20.         else if (ch != whiteSpace)
  21.         {
  22.             // only keep white space if it doesn't succeed/precede CRLF
  23.             // 2: when we `if (k - (i + skipCount) >= 1) = > 0`
  24.             var skipCount = (ch == '\n' || ch == '\r') || (k < s.Length && (s[k] == '\n' || s[k] == '\r')) ? 1 : 2;
  25.  
  26.             // extra space found
  27.             if (k - (i + skipCount) >= 1)
  28.             {
  29.                 s = s.Remove(i + 1, k - (i + skipCount));
  30.             }
  31.  
  32.             // Reset remove length.
  33.             k = -1;
  34.         }
  35.     }
  36.  
  37.     return s;
  38. }
  39.  
  40.  
  41. Note: there is a note that explain why we return 2!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement