Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // This program trims white spaces from begining and end
- // of lines. It also converts multiple spaces inside lines
- // into one single space
- using System;
- using System.Text;
- class WhiteSpace
- {
- public static string FilterWhiteSpaces(string input)
- {
- StringBuilder sb = new StringBuilder(input.Length);
- for (int i = 0; i < input.Length; )
- {
- int first = i;
- char c = input[i];
- int spaceCounter = 0;
- bool endReached = false;
- if (c != ' ') i++; // check for non space
- else
- {
- while (c == ' ') // count spaces
- {
- spaceCounter++;
- i++;
- if (i >= input.Length) // check for end of input
- {
- endReached = true;
- break;
- }
- c = input[i];
- }
- if (!endReached)
- {
- c = input[i - 1];
- }
- }
- if (spaceCounter > 0) // if spaces found
- {
- if (first == 0) continue; // if first line - ignore spaces
- else if (endReached) break; // if end of line - ignore and exit
- else sb.Append(c); // if middle of line - add one space
- }
- else // if non space - add
- {
- sb.Append(c);
- }
- }
- return sb.ToString();
- }
- static void Main()
- {
- int n = int.Parse(Console.ReadLine());
- string[] lines = new string[n];
- for (int i = 0; i < n; i++)
- {
- string line = Console.ReadLine();
- lines[i] = FilterWhiteSpaces(line);
- }
- for (int i = 0; i < n; i++)
- {
- Console.WriteLine(lines[i]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement