BreakIterator Line Breaking Rules

BreakIterator.getLineInstance exposes legal wrap positions at word boundaries so greedy wrapping never splits a word mid-line.

JavaCli Tooling

Code

snippet
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

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 [`.