Iterate each characters of a string : CharacterIterator « Development Class « Java






Iterate each characters of a string


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

public class Main {
  public static void main(String[] args) {
    String text = "The quick brown fox jumps over the lazy dog";
    CharacterIterator it = new StringCharacterIterator(text);

    int vowels = 0;
    int consonants = 0;

    for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
        vowels = vowels + 1;
      } else if (ch != ' ') {
        consonants = consonants + 1;
      }
    }
    System.out.println("Number of vowels: " + vowels);
    System.out.println("Number of consonants: " + consonants);
  }
} 

 








Related examples in the same category

1.Reverse a string using CharacterIterator
2.Iterate a subset of a string
3.Iterating the Characters of a String
4.Iterate over the characters in the backward direction
5.Use CharacterIterator to loop through a string
6.Change the characters
7.Create an iterator on a substring (efgh)