Java Reference
In-Depth Information
int spaces = 0, // Count of spaces
vowels = 0, // Count of vowels
letters = 0; // Count of letters
// Analyze all the characters in the string
int textLength = text.length(); // Get string length
for(int i = 0; i < textLength; i++) {
// Check for vowels
char ch = Character.toLowerCase(text.charAt(i));
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowels++;
//Check for letters
if(Character.isLetter(ch))
letters++;
// Check for spaces
if(Character.isWhitespace(ch))
spaces++;
}
System.out.println("The text contained vowels: " + vowels + "\n" +
" consonants: " + (letters-vowels) + "\n"+
" spaces: " + spaces);
}
}
Running the example, you'll see:
The text contained vowels: 60
consonants: 93
spaces: 37
How It Works
The String variable text is initialized with the quotation you see. All the counting of letter characters
is done in the for loop, which is controlled by the index i . The loop continues as long as i is less than
the length of the string, which is returned by the method text.length() and which we saved in the
variable textLength .
Starting with the first character, which has the index value 0, each character is retrieved from the string by
calling its charAt() method. The loop index i is used as the index to the character position string. The
method returns the character at index position i as a value of type char , and we convert this to lower case,
where necessary, by calling the static method toLowerCase() in the class Character . The character
to be converted is passed as an argument and the method returns either the original character or, if it is upper
case, the lower case equivalent. This enables us to deal with the string in just one case.
There is an alternative to using the toLowerCase() method in the Character class. The String
class also contains a method toLowerCase() that will convert a whole string and return the converted
string. You could convert the string text to lower case with the statement:
Search WWH ::




Custom Search