How to Count Vowels in a String in Java
The Challenge
Count the number of vowels (a, e, i, o, u) in a string!
Solution
Method 1: Using Loop and contains()
String text = "Hello World";
int vowelCount = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < text.length(); i++) {
if (vowels.indexOf(text.charAt(i)) != -1) {
vowelCount++;
}
}
System.out.println("Vowel count: " + vowelCount);
// Output: Vowel count: 3 (e, o, o)Method 2: Using Regex
String text = "Hello World";
int vowelCount = text.replaceAll("[^aeiouAEIOU]", "").length();
System.out.println("Vowel count: " + vowelCount);
// Output: Vowel count: 3Method 3: Using Switch Statement
String text = "Hello World";
int vowelCount = 0;
for (char c : text.toLowerCase().toCharArray()) {
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
vowelCount++;
break;
}
}
System.out.println("Vowel count: " + vowelCount);
// Output: Vowel count: 3Did You Know?
The letter 'y' can sometimes act as a vowel (like in "gym" or "fly"), but it's traditionally classified as a consonant in most programming challenges!
Pro Tip
Use Java 8 streams for a functional approach:
long vowelCount = text.toLowerCase()
.chars()
.filter(c -> "aeiou".indexOf(c) != -1)
.count();Real-World Use Cases
- Linguistics: Analyze text patterns
- Password strength: Check character diversity
- Text games: Word puzzles and challenges
- Data validation: Verify input format
›Short versionOpen if you only have a minute.
- Walk the chars and test membership in a vowel set.
- A lowercase-only set misses A, E, I, O, and U.
- toLowerCase() without a locale follows the default locale. Turkish maps I to ı, not i.
- y is a vowel only if this recipe says so. The page does not count it.
Count vowels
Count characters that belong to the vowel set a, e, i, o, u, ignoring case.
Working approach
- Fold case with toLowerCase(Locale.ROOT) on each character, or on a copy of the string.
- Test "aeiou".indexOf(c) >= 0.
- Leave y, digits, and punctuation uncounted.
Walk the sample
- Input "Java"
- J is not a vowel
- Both a characters match
- The count is 2
The trap
String.toLowerCase() with no locale uses the JVM default. On a Turkish locale, "I" does not become "i", and an English vowel count drops those letters.
static int vowelCount(String text) {
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = Character.toLowerCase(text.charAt(i));
if ("aeiou".indexOf(c) >= 0) {
count++;
}
}
return count;
}Why can "AEIOU" report a vowel count of 0?
The set "aeiou" does not contain A. indexOf looks for the same char.
Fold case first. Prefer Character.toLowerCase(char), which is not the Turkish string rule, or String.toLowerCase(Locale.ROOT) if you lowercase the whole text.
Time O(n), space O(1).
Easy to get wrong
- Comparing only against lowercase literals.
- Calling toLowerCase() with no locale on text that includes I.