Wrap Words To A Fixed Width

Break text into lines no wider than the limit with a greedy pass: fill each line with as many words as fit, then start the next line.

JavaCli Tooling

Code

snippet
import java.util.ArrayList;
import java.util.List;

public class WordWrap {

    // greedy wrap: fill each line up to the width limit, then break
    static List<String> wrap(String text, int width) {
        List<String> lines = new ArrayList<>();
        StringBuilder line = new StringBuilder();
        for (String word : text.split("\\s+")) {
            if (line.length() == 0) {
                line.append(word);
            } else if (line.length() + 1 + word.length() <= width) {
                line.append(' ').append(word);
            } else {
                lines.add(line.toString());
                line = new StringBuilder(word);
            }
        }
        if (line.length() > 0) {
            lines.add(line.toString());
        }
        return lines;
    }

    public static void main(String[] args) {
        String text = "The quick brown fox jumps over the lazy dog again and again";
        for (String line : wrap(text, 20)) {
            System.out.println("|" + line + "|");
        }
    }
}

How it works

Wrap Words To A Fixed Width keeps everything in the class WordWrap and the functions wrap and main.

One loop does the cycling here: for (String word : text.split("\\s+")).

What to watch for

  • The import surface (if any) is all standard library, all versioned with the language itself.

Using it

Entry signature: static List<String> wrap(String text, int width)

Running the file executes main, which drives wrap in order.

Key statements

String text = "The quick brown fox jumps over the lazy dog again and again";
StringBuilder line = new StringBuilder();
List<String> lines = new ArrayList<>();

Interactive Tools for This Topic

FAQ

How do you run Wrap Words To A Fixed Width?
Execute it straight away — the program needs nothing beyond the runtime.