using System;
using System.Collections.Generic;
using System.Text;
class Program
{
static List<string> FormatLines(List<string> words, int maxWidth) {
var result = new List<string>();
var currentLine = new StringBuilder();
int currentLength = 0;
foreach (var word in words) {
int wordLen = word.Length;
// If adding this word exceeds maxWidth, push current line
if (currentLength + (currentLine.Length == 0 ? 0 : 1) + wordLen > maxWidth) {
result.Add(currentLine.ToString());
currentLine.Clear();
currentLine.Append(word);
currentLength = wordLen;
}
else {
if (currentLine.Length > 0) {
currentLine.Append(" ");
currentLength++;
}
currentLine.Append(word);
currentLength += wordLen;
}
}
// Push the last line if not empty
if (currentLine.Length > 0) {
result.Add(currentLine.ToString());
}
return result;
}
static void Main()
{
var words = new List<string> {
"This", "is", "a", "programming", "example", "of", "text", "wrapping"
};
int maxWidth = 12;
var lines = FormatLines(words, maxWidth);
foreach (var line in lines) {
Console.WriteLine($"\"{line}\"");
}
}
}
/*
run:
"This is a"
"programming"
"example of"
"text"
"wrapping"
*/