Line Boundaries
格式化文本或执行换行的应用程序必须找到潜在的换行符。您可以使用getLineInstance
方法创建的BreakIterator
找到这些换行符或边界:
BreakIterator lineIterator =
BreakIterator.getLineInstance(currentLocale);
此BreakIterator
确定字符串 中可以中断文本以在下一行 continue 的位置。 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
的方法将一 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."