Home Tutorial Java Corejava Javatext Iterating the Characters of a String

 
 

Share on Google+Share on Google+
Iterating the Characters of a String
Posted on: April 3, 2006 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Iterating the Characters of a String:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 3, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com