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.
Code
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
Text Wrap FormatterSoft-wrap paragraphs to a chosen column width for emails, commit messages, and terminal output, optionally breaking words longer than the width.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.
FAQ
- How do you run Wrap Words To A Fixed Width?
- Execute it straight away — the program needs nothing beyond the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.