Justify Text To Fixed Width
Split words into lines, then spread leftover spaces across every gap so all lines except the last hit the target width exactly.
Code
import java.util.ArrayList;
import java.util.List;
public class ParagraphJustify {
// 两端对齐(full justify):剩余空格均摊到行内所有词隙;
// 最后一行或单行不做拉伸,用普通空格连接
static List<String> justify(List<String> words, int width) {
List<String> lines = new ArrayList<>();
int i = 0;
while (i < words.size()) {
int len = words.get(i).length();
int j = i + 1;
while (j < words.size() && len + 1 + words.get(j).length() <= width) {
len += 1 + words.get(j).length();
j++;
}
StringBuilder line = new StringBuilder(words.get(i));
if (j == words.size() || j - i == 1) {
for (int k = i + 1; k < j; k++) {
line.append(' ').append(words.get(k));
}
} else {
int gaps = j - i - 1;
int spaces = (width - len) + gaps; // 每个词隙保底 1 个 + 待分配
int base = spaces / gaps;
int extra = spaces % gaps;
for (int k = i + 1; k < j; k++) {
for (int s = 0; s < base + (k - i <= extra ? 1 : 0); s++) {
line.append(' ');
}
line.append(words.get(k));
}
}
lines.add(line.toString());
i = j;
}
return lines;
}
public static void main(String[] args) {
List<String> words = List.of("Packaging", "decisions", "must", "be", "made",
"with", "real", "size", "budgets", "not", "guesses");
for (String line : justify(words, 20)) {
System.out.println("|" + line + "|");
}
}
}How execution unfolds
Justify Text To Fixed Width reduces to the class ParagraphJustify and the functions justify and main.
The file repeats itself only inside while (i < words.size()).
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
The entry-point signature is static List<String> justify(List<String> words, int width)
Treat main as the orchestrator calling justify in a fixed order.
Key statements
len += 1 + words.get(j).length();
Interactive Tools for This Topic
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.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.
FAQ
- How do you run Justify Text To Fixed Width?
- Just run the file; everything it needs ships with the runtime itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.