CharacterIterator
This interface defines a protocol for bidirectional iteration over text. The iterator iterates over a bounded sequence of characters. Characters are indexed with values beginning with the value returned by getBeginIndex() and continuing through the value returned by getEndIndex()-1.
Iterators maintain a current character index, whose valid range is from getBeginIndex() to getEndIndex(); the value getEndIndex() is included to allow handling of zero-length text ranges and for historical reasons. The current index can be retrieved by calling getIndex() and set directly by calling setIndex(), first(), and last().
The methods previous() and next() are used for iteration. They return DONE if they would move outside the range from getBeginIndex() to getEndIndex() -1, signaling that the iterator has reached the end of the sequence. DONE is also returned by other methods to indicate that the current index is outside this range.
Examples:
Traverse the text from start to finish {@snippet lang=java :
public void traverseForward(CharacterIterator iter) {
for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {Content copied to clipboardprocessChar(c);Content copied to clipboard}Content copied to clipboard}
}
Traverse the text backwards, from end to start {@snippet lang=java :
public void traverseBackward(CharacterIterator iter) {
for (char c = iter.last(); c != CharacterIterator.DONE; c = iter.previous()) {Content copied to clipboardprocessChar(c);Content copied to clipboard}Content copied to clipboard}
}
Traverse both forward and backward from a given position in the text. Calls to notBoundary() in this example represents some additional stopping criteria. {@snippet lang=java :
public void traverseOut(CharacterIterator iter, int pos) {
for (char c = iter.setIndex(pos);Content copied to clipboardc != CharacterIterator.DONE && notBoundary(c);Content copied to clipboardc = iter.next()) {Content copied to clipboard}Content copied to clipboardint end = iter.getIndex();Content copied to clipboardfor (char c = iter.setIndex(pos);Content copied to clipboardc != CharacterIterator.DONE && notBoundary(c);Content copied to clipboardc = iter.previous()) {Content copied to clipboard}Content copied to clipboardint start = iter.getIndex();Content copied to clipboardprocessSection(start, end);Content copied to clipboard}
}
Since
1.1