Count Vowels With Loop

Description: Counts the number of vowels in a given string using a looping mechanism. It doesn't take into account that sometimes "Y" is considered a vowel in some situations.
Tested Platform: Java SE 7, Windows 7
Language: Java
public int countVowels(String str) {
		int count = 0;
		
		if (str.length() > 0) {
			String vowels = "aeiou";
			
			// Loop through each letter of string, lowercase it and look for it
			// in our string of vowels.
			for (int i = 0; i < str.length(); i++) {
				if (vowels.indexOf(str.toLowerCase().charAt(i)) != -1) {
					count++;
				}
			}
		}
		
		return count;
}

Submitted: October 23, 2012

Return to the snippets listing