线边界

原文: https://docs.oracle.com/javase/tutorial/i18n/text/line.html

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

  1. BreakIterator lineIterator =
  2. BreakIterator.getLineInstance(currentLocale);

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

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

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

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

在连字符后立即发生潜在的换行:

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

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

  1. static void formatLines(
  2. String target, int maxLength,
  3. Locale currentLocale) {
  4. BreakIterator boundary = BreakIterator.
  5. getLineInstance(currentLocale);
  6. boundary.setText(target);
  7. int start = boundary.first();
  8. int end = boundary.next();
  9. int lineLength = 0;
  10. while (end != BreakIterator.DONE) {
  11. String word = target.substring(start,end);
  12. lineLength = lineLength + word.length();
  13. if (lineLength >= maxLength) {
  14. System.out.println();
  15. lineLength = word.length();
  16. }
  17. System.out.print(word);
  18. start = end;
  19. end = boundary.next();
  20. }
  21. }

BreakIteratorDemo程序调用formatLines方法如下:

  1. String moreText =
  2. "She said, \"Hello there,\" and then " +
  3. "went on down the street. When she stopped " +
  4. "to look at the fur coats in a shop + "
  5. "window, her dog growled. \"Sorry Jake,\" " +
  6. "she said. \"I didn't know you would take " +
  7. "it personally.\"";
  8. formatLines(moreText, 30, currentLocale);

此调用formatLines的输出是:

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