One of the fundamental tasks in string manipulation is counting the number of vowels in a given string. This problem is often asked in interviews to test your understanding of basic string operations and control flow. The task requires you to iterate over each character in the string, check if it's a vowel, and then count how many vowels appear.
In this article, we will explore how to count the number of vowels (a, e, i, o, u) in a string using Java. We will cover a simple approach using loops and conditional statements and provide multiple solutions, including a more optimized approach.
Given a string, you need to count how many vowels (a, e, i, o, u, both uppercase and lowercase) appear in the string.
For example
- Input: "Hello World"
- Output: 3 (vowels are 'e', 'o', and 'o')
Approach 1. Using a Simple Loop
The most straightforward approach to solve this problem is by iterating over each character of the string, checking if it is a vowel, and keeping a count of how many vowels are found.
Algorithm
- Convert the string to lowercase or uppercase to handle both cases uniformly.
- Initialize a counter to zero.
- Loop through each character of the string.
- Check if the character is a vowel.
- If it is, increment the counter.
- After the loop, return the final count.
Code Implementation
public class VowelCounter {
// Method to count vowels in a string
public static int countVowels(String str) {
// Convert the string to lowercase to handle case insensitivity
str = str.toLowerCase();
int count = 0;
// Loop through each character of the string
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// Check if the character is a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
count++;
}
}
return count;
}
public static void main(String[] args) {
String input = "Hello World";
int result = countVowels(input);
System.out.println("Number of vowels: " + result);
}
}
Explanation of the Code
- Convert to lowercase: To handle both uppercase and lowercase vowels uniformly, we convert the string to lowercase using str.toLowerCase().
- Loop through the string: We use a for loop to iterate through each character of the string using str.charAt(i).
- Check for vowels: The condition if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') checks if the character is a vowel.
- Count vowels: If a vowel is found, we increment the count.
- Return result: After the loop finishes, the count variable holds the total number of vowels, which is then returned.
Output
Approach 2. Using a Set for Vowel Checking
In the previous approach, we manually checked for vowels in a string using a series of if statements. A more efficient way to check for vowels is to use a Set. Using a Set allows us to check membership in constant time (O(1)), which may be more efficient, especially for larger strings.
Code Implementation
import java.util.HashSet;
import java.util.Set;
public class VowelCounterApp {
// Method to count vowels using a Set
public static int countVowels(String str) {
// Set of vowels for quick lookup
Set<Character> vowels = new HashSet<>();
vowels.add('a');
vowels.add('e');
vowels.add('i');
vowels.add('o');
vowels.add('u');
int count = 0;
// Convert the string to lowercase to handle both cases
str = str.toLowerCase();
// Loop through each character of the string
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
// Check if the character is a vowel using the Set
if (vowels.contains(ch)) {
count++;
}
}
return count;
}
public static void main(String[] args) {
String input = "Hello World";
int result = countVowels(input);
System.out.println("Number of vowels: " + result);
}
}
Explanation of the Code
- Using a Set for vowels: We use a HashSet<Character> to store the vowels. The Set provides constant-time lookups to check if a character is a vowel.
- Set membership check: The condition if (vowels.contains(ch)) checks if the character is in the Set of vowels.
- Rest of the logic: The rest of the logic remains the same as in the previous approach.
Output
Conclusion
Counting the number of vowels in a string is a basic yet essential problem in string manipulation. By using simple loops and conditional checks or leveraging data structures like a Set, we can efficiently solve the problem in linear time.
- Approach 1 (Using a Loop and If Statements) is straightforward and easy to understand.
- Approach 2 (Using a Set) optimizes the vowel-checking process by utilizing constant-time lookups, which can be especially beneficial in larger or more complex problems.
Both approaches are effective, and the best method depends on your specific requirements, such as code simplicity or performance.