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 19, Windows 10
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;
}

Posted: March 20, 2023

Return to the snippets listing