Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // За обяснения по source code посетете: http://yordanbonev.wordpress.com/
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- class ConsoleJustifyMethod
- {
- static void Main()
- {
- int numberOfLines = int.Parse(Console.ReadLine());
- int numberOfSymbols = int.Parse(Console.ReadLine());
- StringBuilder text = new StringBuilder();
- for (int i = 0; i < numberOfLines; i++)
- {
- text.Append(Console.ReadLine());
- text.Append(" ");
- }
- char[] separators = new char[] { ' ' };
- string[] splittedText = text.ToString().Split(separators, StringSplitOptions.RemoveEmptyEntries);
- OutputJustifyText(splittedText, numberOfSymbols);
- }
- static void OutputJustifyText(string[] splittedText, int numberOfSymbols)
- {
- StringBuilder outputText = new StringBuilder();
- int spaceCounter = 2;
- for (int i = 0; i < splittedText.Length; i++)
- {
- if (((outputText.ToString() + splittedText[i]).Length <= numberOfSymbols))
- {
- outputText.Append(splittedText[i]);
- if ((outputText.ToString() + " ").Length < numberOfSymbols)
- {
- outputText.Append(" ");
- }
- }
- else
- {
- AddOrRemoveSpaces(outputText, numberOfSymbols, spaceCounter);
- outputText.Append(splittedText[i] + " ");
- }
- }
- AddOrRemoveSpaces(outputText, numberOfSymbols, spaceCounter);
- return;
- }
- static void AddOrRemoveSpaces(StringBuilder outputText, int numberOfSymbols, int spaceCounter)
- {
- if (outputText[outputText.Length - 1] == ' ')
- {
- outputText.Remove(outputText.Length - 1, 1);
- }
- int index = outputText.ToString().IndexOf(' ', 0);
- if (index == -1)
- {
- Console.WriteLine(outputText.ToString().TrimEnd(' '));
- outputText.Clear();
- }
- int firstIndex = index;
- while (index != -1)
- {
- if (outputText.Length == numberOfSymbols)
- {
- Console.WriteLine(outputText.ToString().TrimEnd(' '));
- outputText.Clear();
- spaceCounter = 2;
- break;
- }
- else
- {
- outputText.Insert(index, ' ');
- index = outputText.ToString().IndexOf(' ', index + spaceCounter);
- }
- if (index == -1)
- {
- spaceCounter++;
- index = firstIndex;
- }
- }
- return;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement