Advertisement
stoianpp

ConsoleJustification

Dec 30th, 2013
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.93 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. class ConsoleJustification
  6. {
  7.     static void Main()
  8.     {
  9.         int lines =  int.Parse(Console.ReadLine());
  10.         int width = int.Parse(Console.ReadLine());
  11.         StringBuilder text = new StringBuilder();
  12.         for (int i = 0; i < lines; i++)
  13.         {
  14.             text.Append(Console.ReadLine());
  15.             text.Append(' ');
  16.         }
  17.         string strText = text.ToString();
  18.         List<string> words = new List<string>();
  19.         char[] separators = { ' ', ' ' };
  20.         words.AddRange(strText.Split(separators,StringSplitOptions.RemoveEmptyEntries));
  21.         Printing(words, width);
  22.     }
  23.  
  24.     static void Printing (List<string> words, int width)
  25.     {
  26.         StringBuilder printLine = new StringBuilder();
  27.         while (words.Count > 0)
  28.         {
  29.             int wordsOnRow = 0;
  30.             if (printLine.Length == 0)
  31.             {
  32.                 printLine.Append(words[0]);
  33.                 words.RemoveAt(0);
  34.                 wordsOnRow++;
  35.             }
  36.             while (words.Count>0 && (width - (printLine.Length + 1) >= words[0].Length))
  37.             {
  38.                 printLine.Append(' ');
  39.                 printLine.Append(words[0]);
  40.                 words.RemoveAt(0);
  41.                 wordsOnRow++;
  42.             }
  43.             Console.WriteLine(Justification(printLine,width,wordsOnRow));
  44.             printLine.Clear();
  45.         }  
  46.     }
  47.  
  48.     static string Justification(StringBuilder printLine, int width, int wordsOnRow)
  49.     {
  50.         int position = 1;
  51.         while (printLine.Length < width && wordsOnRow != 1)
  52.         {
  53.             if (printLine[position] == ' ' && printLine[position-1] != ' ')
  54.             {
  55.                 printLine.Insert(position,' ');
  56.             }
  57.             if (position == printLine.Length-1) position = 1;
  58.             position++;
  59.         }
  60.         return printLine.ToString();
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement