The following example show you how to iterate each character of a string using the java.text.CharacterIterator
and java.text.StringCharacterIterator
to count the number of vowels and consonants in the string.
package org.kodejava.text;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
public class StringCharacterIteratorExample {
private static final String text =
"The quick brown fox jumps over the lazy dog";
public static void main(String[] args) {
CharacterIterator it = new StringCharacterIterator(text);
int vowels = 0;
int consonants = 0;
// Iterates character sets from the beginning to the last character
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);
}
}
The output of the code snippet above:
Number of vowels: 11
Number of consonants: 24
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024