Advertisement
ivan_yosifov

White_Space_Filter

Dec 11th, 2013
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. // This program trims white spaces from begining and end
  2. // of lines. It also converts multiple spaces inside lines
  3. // into one single space
  4.  
  5. using System;
  6. using System.Text;
  7.  
  8. class WhiteSpace
  9. {
  10.     public static string FilterWhiteSpaces(string input)
  11.     {
  12.         StringBuilder sb = new StringBuilder(input.Length);
  13.         for (int i = 0; i < input.Length; )
  14.         {
  15.             int first = i;
  16.             char c = input[i];
  17.             int spaceCounter = 0;
  18.             bool endReached = false;
  19.             if (c != ' ') i++;  // check for non space
  20.             else
  21.             {
  22.                 while (c == ' ') // count spaces
  23.                 {
  24.                     spaceCounter++;
  25.                     i++;
  26.                     if (i >= input.Length) // check for end of input
  27.                     {
  28.                         endReached = true;
  29.                         break;
  30.                     }
  31.                     c = input[i];
  32.                 }
  33.                 if (!endReached)
  34.                 {
  35.                     c = input[i - 1];
  36.                 }
  37.             }
  38.             if (spaceCounter > 0) // if spaces found
  39.             {
  40.                 if (first == 0) continue; // if first line - ignore spaces
  41.                 else if (endReached) break; // if end of line - ignore and exit
  42.                 else sb.Append(c); // if middle of line - add one space
  43.             }
  44.             else // if non space - add
  45.             {
  46.                 sb.Append(c);
  47.             }
  48.         }
  49.         return sb.ToString();
  50.     }
  51.     static void Main()
  52.     {
  53.         int n = int.Parse(Console.ReadLine());
  54.         string[] lines = new string[n];
  55.         for (int i = 0; i < n; i++)
  56.         {
  57.             string line = Console.ReadLine();
  58.             lines[i] = FilterWhiteSpaces(line);            
  59.         }
  60.         for (int i = 0; i < n; i++)
  61.         {
  62.             Console.WriteLine(lines[i]);
  63.         }
  64.     }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement