Sunday, January 26, 2014

Iterate over all the chars in a String

Source:
public class IterateChars {
   public static void main(String[] args) {
      String str = "abcdefg";
      int n=0;
      for (char c : str.toCharArray()) {
         System.out.println("pos " + n++ + " : " + c);
      }
   }
}

Output:
   $ java IterateChars 
   pos 0 : a
   pos 1 : b
   pos 2 : c
   pos 3 : d
   pos 4 : e
   pos 5 : f
   pos 6 : g

Blog Archive