Line Boundaries

格式化文本或执行换行的应用程序必须找到潜在的换行符。您可以使用getLineInstance方法创建的BreakIterator找到这些换行符或边界:

BreakIterator lineIterator =
    BreakIterator.getLineInstance(currentLocale);

BreakIterator确定字符串 中可以中断文本以在下一行 continue 的位置。 BreakIterator检测到的位置是潜在的换行符。屏幕上显示的实际换行符可能不同。

以下两个示例使用BreakIteratorDemo.javamarkBoundaries方法来显示BreakIterator检测到的线边界。 markBoundaries方法通过在目标字符串 下方打印插入符号(^)来指示行边界。

根据BreakIterator,在一系列空格字符(空格,制表符,换行符)终止之后会出现行边界。在以下示例中,请注意,您可以在检测到的任何边界处折断行:

She stopped.  She said, "Hello there," and then went on.
^   ^         ^   ^     ^      ^     ^ ^   ^    ^    ^  ^

连字符后也可能会出现换行符:

There are twenty-four hours in a day.
^     ^   ^      ^    ^     ^  ^ ^   ^

下一个示例使用称为formatLines的方法将一 LongString 文本分成固定 Long 度的行。此方法使用BreakIterator定位潜在的换行符。 formatLines方法简短,简单,并且由于BreakIterator而与语言环境无关。这是源代码:

static void formatLines(
    String target, int maxLength,
    Locale currentLocale) {

    BreakIterator boundary = BreakIterator.
        getLineInstance(currentLocale);
    boundary.setText(target);
    int start = boundary.first();
    int end = boundary.next();
    int lineLength = 0;

    while (end != BreakIterator.DONE) {
        String word = target.substring(start,end);
        lineLength = lineLength + word.length();
        if (lineLength >= maxLength) {
            System.out.println();
            lineLength = word.length();
        }
        System.out.print(word);
        start = end;
        end = boundary.next();
    }
}

BreakIteratorDemo程序按以下方式调用formatLines方法:

String moreText =
    "She said, \"Hello there,\" and then " +
    "went on down the street. When she stopped " +
    "to look at the fur coats in a shop + "
    "window, her dog growled. \"Sorry Jake,\" " +
    "she said. \"I didn't know you would take " +
    "it personally.\"";

formatLines(moreText, 30, currentLocale);

此调用到formatLines的输出为:

She said, "Hello there," and
then went on down the
street. When she stopped to
look at the fur coats in a
shop window, her dog
growled. "Sorry Jake," she
said. "I didn't know you
would take it personally."