The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.text  [26 examples]

e307. Iterating the Characters of a String

    CharacterIterator it = new StringCharacterIterator("abcd");
    
    // Iterate over the characters in the forward direction
    for (char ch=it.first(); ch != CharacterIterator.DONE; ch=it.next()) {
        // Use ch ...
    }
    
    // Iterate over the characters in the backward direction
    for (char ch=it.last(); ch != CharacterIterator.DONE; ch=it.previous()) {
        // Use ch ...
    }
    
    // Other methods
    char ch = it.first();      // a
    ch = it.current();         // a
    ch = it.next();            // b
    ch = it.current();         // b
    ch = it.last();            // d
    int pos = it.getIndex();   // 3
    ch = it.next();            // DONE
    pos = it.getIndex();       // 4
    ch = it.previous();        // d
    ch = it.setIndex(1);       // b
    
    // Change the characters
    ((StringCharacterIterator)it).setText("efgh");
    ch = it.current();         // e
    
    // Create an iterator on a substring (efgh)
    int begin = 5;
    int end = 9;
    pos = 6;
    it = new StringCharacterIterator("abcd efgh ijkl", begin, end, pos);
    ch = it.current();         // f
    ch = it.last();            // h

 Related Examples
e305. Determining the Type of a Character
e306. Comparing Strings in a Locale-Independent Way
e308. Adding an Attribute to a String
e309. Incrementing a Double by the Smallest Possible Amount
e310. Localizing Messages

See also: Dates    Messsages    Numbers    Times    Words and Sentences   


© 2002 Addison-Wesley.