Processing a String One Character at a Time

for (int index = 0; index < string1.length();
											index++) {
											char aChar = string1.charAt(index);
											}

The charAt() method allows you to obtain a single character from the string at the specified index. The characters are indexed 0 based, from 0 to the length of the string-1. The phrase shown previously loops through each character contained in string1.

An alternative method would be to use the StringReader class, as follows:

StringReader reader = new StringReader(string1);
int singleChar = reader.read();

Using this mechanism, the read() method of the StringReader class returns one character at a time, as an integer. Each time the read() method is called, the next character of the string will be returned.

Get Java™ Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.