O'Reilly logo

Java™ Phrasebook by Timothy Fisher

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required