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

1 Answer

0 votes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WordWrap {

    public static List<String> formatLines(List<String> words, int maxWidth) {
        List<String> result = new ArrayList<>();
        StringBuilder currentLine = new StringBuilder();
        int currentLength = 0;

        for (String word : 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 = new StringBuilder(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;
    }

    public static void main(String[] args) {
        List<String> words = Arrays.asList(
            "This", "is", "a", "programming", "example", "of", "text", "wrapping"
        );
        int maxWidth = 12;

        List<String> lines = formatLines(words, maxWidth);

        for (String line : lines) {
            System.out.println("\"" + line + "\"");
        }
    }
}



/*
run:

"This is a"
"programming"
"example of"
"text"
"wrapping"

*/

 



answered Dec 2, 2025 by avibootz

Related questions

...