Java 教程是为 JDK 8 编写的。本页中描述的示例和实践未利用在后续版本中引入的改进。
格式化文本或执行换行的应用程序必须找到潜在的换行符。你可以使用 getLineInstance
方法创建的 BreakIterator
找到这些换行符或边界:
BreakIterator lineIterator = BreakIterator.getLineInstance(currentLocale);
此 BreakIterator
确定字符串中的位置,文本可以在下一行中断开以继续。BreakIterator
检测到的位置是潜在的换行符。屏幕上显示的实际换行符可能不一样。
以下两个示例使用 BreakIteratorDemo.java
的 markBoundaries
方法来显示检测到的行边界 BreakIterator
。markBoundaries
方法通过在目标字符串下打印插入符号(^)来指示行边界。
根据 BreakIterator
,在一系列空白字符(空格,制表符,换行符)终止后出现行边界。在以下示例中,请注意你可以在检测到的任何边界处断开行:
She stopped. She said, "Hello there," and then went on. ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^
在连字符后立即发生潜在的换行:
There are twenty-four hours in a day. ^ ^ ^ ^ ^ ^ ^ ^ ^
下一个示例使用名为 formatLines
的方法将一长串文本分成固定长度的行。此方法使用 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."