线边界
原文: https://docs.oracle.com/javase/tutorial/i18n/text/line.html
格式化文本或执行换行的应用程序必须找到潜在的换行符。您可以使用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," andthen went on down thestreet. When she stopped tolook at the fur coats in ashop window, her doggrowled. "Sorry Jake," shesaid. "I didn't know youwould take it personally."
