Java How To - Count Vowels in a String
Count Vowels in a String
Loop through each character and count a, e, i, o, u
(case-insensitive).
Example
String text = "Hello Java";
int count = 0;
for (char c : text.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
count++;
}
}
System.out.println("Vowels: " + count);
Explanation: We convert the string to lowercase, loop through each character, and count whenever we see a vowel.
General Example
The example above checks each vowel with multiple conditions. That works fine, but if you want a more general solution, you can store the vowels in a Set
and check characters against it:
Example
import java.util.Set;
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
String text = "Hello Java";
Set<Character> vowels = new HashSet<>();
for (char v : new char[]{'a','e','i','o','u'}) {
vowels.add(v);
}
int count = 0;
for (char c : text.toLowerCase().toCharArray()) {
if (vowels.contains(c)) {
count++;
}
}
System.out.println("Vowels: " + count);
}
}
Explanation: We first add all vowels to a Set
. Then we loop through the characters of the string (converted to lowercase). Each character is checked against the set, and if it exists, the counter goes up. This method is easier to extend if you want to count other characters (like consonants, digits, or symbols).