In this article, we will learn how to write a Java program to calculate the total number of vowels in each string in an array. This problem is a great example of practicing working with arrays and string manipulation in Java.
Problem statement:
We are given an array of strings, and the task is to calculate the total number of vowels (a, e, i, o, u) present in each string. The output will show the count of vowels for each string in the array.
Approach to Solve the Problem
- Iterate Through the Array: Use a loop to iterate through each string in the array.
- Check for Vowels: For each string, check each character to see if it is a vowel.
- Count Vowels: Maintain a counter to track the number of vowels in each string.
- Display Results: Print the number of vowels for each string.
Java Program for Counting Vowels in each String in an Array
Here is the Java program to solve the problem, this program considers both lowercase and uppercase vowels (e.g., ‘A’ and ‘a’).
public class VowelCounter {
public static void main(String[] args) {
// Input array of strings
String[] words = {"hello", "world", "java", "programming"};
// Loop through each word in the array
for (String word : words) {
int vowelCount = countVowels(word);
System.out.println("The word \"" + word + "\" contains " + vowelCount + " vowels.");
}
}
// Method to count vowels in a string
public static int countVowels(String word) {
int count = 0;
String vowels = "aeiouAEIOU"; // Vowels in both lowercase and uppercase
// Check each character in the string
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
if (vowels.indexOf(ch) != -1) { // Check if the character is a vowel
count++;
}
}
return count;
}
}
OUTPUT:
The word “hello” contains 2 vowels.
The word “world” contains 1 vowels.
The word “java” contains 2 vowels.
The word “programming” contains 3 vowels.
Code Explanation:
- We define an array of strings
words
containing the words for which we need to count the vowels. - We use a
for-each
loop to iterate through each word in the array. - countVowels() Method:
- This method takes a string as input and returns the count of vowels in that string.
- A string
vowels
is defined, as containing all vowels (both uppercase and lowercase). - Each character in the input string is checked against the
vowels
string using theindexOf
method. If the character is a vowel, the counter is incremented.
You can learn the Top 20 string array programs for interview preparation (Click here).