Java Data Type How to - Is a Character letter or white space








Question

We would like to know how to is a Character letter or white space.

Answer

public class StringCharacters {
  public static void main(String[] args) {
    String text = "To be or not to be?";
//  w  w  w  .j a v  a 2  s  .  c o  m
    int spaces = 0,
    vowels = 0, 
    letters = 0;

    for (int i = 0; i < text.length(); i++) {
      char ch = Character.toLowerCase(text.charAt(i));
      if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
        ++vowels;
      if (Character.isLetter(ch))
        ++letters;
      if (Character.isWhitespace(ch))
        ++spaces;
    }
  }
}

The code above generates the following result.