Let’s say the following is our string −
String myStr = "Jamie";
Set variable count = 0, since we will be calculating the vowels in the same variable. Loop through every character and count vowels −
for(char ch : myStr.toCharArray()) {
ch = Character.toLowerCase(ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++count;
}Example
Following is an example to count vowels in a string −
public class Demo {
public static void main(String[] args) {
String myStr = "Jamie";
int count = 0;
System.out.println("String = "+myStr);
for(char ch : myStr.toCharArray()) {
ch = Character.toLowerCase(ch);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
++count;
}
}
System.out.println("Vowels = "+count);
}
}Output
String = Jamie Vowels = 3