Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,230 questions

56,132 answers

573 users

How to format an array of strings in lines with maxWidth without breaking the words in C#

1 Answer

0 votes
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"

*/

 



answered Dec 2, 2025 by avibootz

Related questions

...