Detecting Text Boundaries |
Applications that format text or perform line wrapping must locate potential line breaks. You can find these line breaks, or boundaries, with aBreakIterator
that has been created with thegetLineInstance
method:ThisBreakIterator lineIterator = BreakIterator.getLineInstance(currentLocale);BreakIterator
determines the positions in a string where text can break to continue on the next line. The positions detected by theBreakIterator
are potential line breaks. The actual line breaks displayed on the screen may not be the same.In the two examples that follow, we'll use the markBoundaries method to view the line boundaries detected by a
BreakIterator
. This method prints marks line boundaries by printing carets ('^') beneath the target string.According to a
BreakIterator
, a line boundary occurs after the end of a sequence of whitespace characters (space, tab, newline). In the following example, note that we can break the line at any of the boundaries detected:She stopped. She said, "Hello there," and then went on. ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^Potential line breaks also occur immediately after a hyphen:
In the next example, we break a long string of text into fixed length lines with a method calledThere are twenty-four hours in a day. ^ ^ ^ ^ ^ ^ ^ ^ ^formatLines
. We use aBreakIterator
to locate the potential line breaks. To break a line, we execute aSystem.out.println()
whenever the length of the current line reaches themaxLength
parameter. TheformatLines
method is short, simple, and thanks to theBreakIterator
, locale-independent. Here is the source code:In the BreakIteratorDemo.java program, we invokestatic 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(); } }formatLines
as follows:The output from this call toString 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
is: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."
Detecting Text Boundaries |