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.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net