Iterating the Characters of a String


 

Iterating the Characters of a String

This section illustrates you how to iterate the characters of a string.

This section illustrates you how to iterate the characters of a string.

Iterating the Characters of a String

This section illustrates you how to iterate the characters of a string.

For bi-directional iteration over the text , you can use the CharacterIterator interaface. StringCharacterIterator implements this interface for the string. In CharacterIterator, characters are indexed with values beginning with the value returned by getBeginIndex() and continuing through the value returned by getEndIndex()-1.

In the given example, we have used CharacterIterator interface along with the class StringCharacterIterator to iterate the characters of the specified string. To iterate over the characters in the forward direction and display all of them separately, we have used the following code:

for (char ch = it.setIndex(0); ch != CharacterIterator.DONE; ch = it.next()){
System.
out.println(ch);
}

setIndex(): This method CharacterIterator sets the position to the specified position in the text and returns that character.

CharacterIterator.DONE: This field returns the constant when the iterator has reached either the end or the beginning of the text.

next():  This method of CharacterIterator increments the iterator's index by one and returns the character at the new index.

Here is the code:

import java.text.*;

public class IteratingCharacters {
	public static void main(String[] args) {
		CharacterIterator it = new StringCharacterIterator("hello");
		for (char ch = it.setIndex(0); ch != CharacterIterator.DONE; ch = it
				.next()) {
			System.out.println(ch);
		}
	}
}

Output:

h
e
l
l
o

Ads