Iterating the Characters of a String - Java Language Basics

Java examples for Language Basics:char

Description

Iterating the Characters of a String

Demo Code

import java.text.CharacterIterator;
import java.text.StringCharacterIterator;

public class Main {
  public static void main(String[] argv) {
    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 ...
    }//from  ww  w . j a  va 2s.co m

    // 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
    System.out.println(ch);
    ch = it.last(); // d
    int pos = it.getIndex(); // 3
    System.out.println(ch);
    ch = it.next(); // DONE
    pos = it.getIndex(); // 4
    System.out.println(ch);
    ch = it.previous(); // d
    System.out.println(ch);
    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(); 
    System.out.println(ch);

    ch = it.last(); 
    System.out.println(ch);
  }
}

Result


Related Tutorials