BreakIterator Line Breaking Rules
BreakIterator.getLineInstance exposes legal wrap positions at word boundaries so greedy wrapping never splits a word mid-line.
Code
import java.text.BreakIterator;
import java.util.Locale;
public class BreakIteratorLineWrapping {
public static void main(String[] args) {
String notice = "Deploy payment today";
// getLineInstance:换行点落在单词边界(空格按惯例挂在行尾)
BreakIterator lines = BreakIterator.getLineInstance(Locale.US);
lines.setText(notice);
int start = lines.first();
for (int end = lines.next(); end != BreakIterator.DONE; end = lines.next()) {
System.out.println("segment [" + start + "," + end + ") = '"
+ notice.substring(start, end) + "'");
start = end;
}
// 贪心断行:超过宽度就在上一个合法断行点切开,单词不会被劈开
int width = 12;
int lineStart = lines.first();
start = lines.first();
for (int end = lines.next(); end != BreakIterator.DONE; end = lines.next()) {
if (end - lineStart > width) {
System.out.println("wrapped [" + notice.substring(lineStart, start).stripTrailing() + "]");
lineStart = start;
}
start = end;
}
System.out.println("wrapped [" + notice.substring(lineStart).stripTrailing() + "]");
}
}How it works
The code’s whole job belongs to the class BreakIteratorLineWrapping and the function main.
A single loop drives the file — for (int end = lines.next(); end != BreakIterator.DONE; end = lines.next()).
Caveats
- No dependencies section needed; the standard library is the whole story.
Using it
Its public face is public static void main(String[] args)
The run marks each line — segment [, wrapped [ — when the file runs.
Key statements
BreakIterator lines = BreakIterator.getLineInstance(Locale.US);
String notice = "Deploy payment today";
int lineStart = lines.first();
Interactive Tools for This Topic
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.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does BreakIterator Line Breaking Rules print when run?
- Execute the whole file; each printed line is prefixed with a label like `segment [`, `wrapped [`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.