Write A Program To Count The Number Of Vowels And Consonants In A Given String In Java
Counting vowels and consonants in a string is a common programming challenge that introduces fundamental string manipulation and character processing concepts. In this article, you will learn how to approach this problem in Java using various techniques, from basic iteration to more advanced methods like regular expressions and streams.
Problem Statement
The goal is to write a program that takes a given string as input and accurately determines the total number of vowels and consonants it contains. This task requires careful handling of case sensitivity, non-alphabetic characters, and efficient character classification.
Example
For the input string: "Hello World123!"
The desired output would be: Vowels: 3 Consonants: 7
Background & Knowledge Prerequisites
To effectively understand the solutions presented, readers should have a basic understanding of:
- Java Fundamentals: Variables, data types, loops (for, while), conditional statements (if-else).
- String Manipulation: Accessing characters within a string (
charAt()), string length (length()). - Character Class: Methods like
Character.isLetter(),Character.toLowerCase(). - Optional: Basic knowledge of regular expressions (regex) and Java 8 Streams for advanced approaches.
Use Cases or Case Studies
Counting vowels and consonants, while seemingly simple, has practical applications in various domains:
- Text Analysis: Used in natural language processing (NLP) to analyze linguistic patterns, phonetics, or readability scores.
- Data Validation: Can be part of validating specific input formats, such as ensuring a password contains a certain number of alphabetic characters.
- Educational Tools: Helps in developing language learning applications, especially for phonics or speech therapy.
- Cryptography: Simple character frequency analysis can sometimes be a building block in understanding basic ciphers.
- Game Development: Creating word games or puzzles that involve character types.
Solution Approaches
Here are a few ways to count vowels and consonants in a Java string.
Approach 1: Basic Iteration with If-Else
This is the most straightforward method, involving iterating through each character of the string and using conditional logic to classify them.
- Summary: Iterate through each character, convert it to lowercase, and check if it's a vowel. If not a vowel but an alphabet, it's a consonant.
// Count Vowels and Consonants - Basic Iteration
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize Scanner and get input string
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
scanner.close();
// Step 2: Initialize counters
int vowelCount = 0;
int consonantCount = 0;
// Step 3: Iterate through each character of the string
for (int i = 0; i < inputString.length(); i++) {
char ch = inputString.charAt(i);
// Step 4: Convert character to lowercase for case-insensitive comparison
char lowerCh = Character.toLowerCase(ch);
// Step 5: Check if the character is an alphabet
if (Character.isLetter(lowerCh)) {
// Step 6: Check if it's a vowel
if (lowerCh == 'a' || lowerCh == 'e' || lowerCh == 'i' || lowerCh == 'o' || lowerCh == 'u') {
vowelCount++;
} else {
// Step 7: If not a vowel but an alphabet, it's a consonant
consonantCount++;
}
}
}
// Step 8: Print the results
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
}
}
- Sample Output:
Enter a string: Hello World123! Vowels: 3 Consonants: 7
- Stepwise Explanation:
- The program prompts the user to enter a string.
vowelCountandconsonantCountare initialized to zero.- A
forloop iterates from the first character to the last. - In each iteration, the character at the current index is retrieved using
charAt(i). Character.toLowerCase()converts the character to its lowercase equivalent to ensure case-insensitive checking.Character.isLetter()first checks if the character is an alphabet. This prevents counting numbers, spaces, or symbols as either vowels or consonants.- Inside the
if (Character.isLetter())block, anotherif-elsestatement checks if the lowercase character matches any of the vowels ('a', 'e', 'i', 'o', 'u'). - If it's a vowel,
vowelCountis incremented; otherwise,consonantCountis incremented. - Finally, the total counts are printed.
Approach 2: Using Regular Expressions (Regex)
Regular expressions provide a powerful way to define patterns and search for them in strings. This approach can be more concise for matching specific character sets.
- Summary: Use regex patterns to find and count vowels and then count letters that are not vowels as consonants.
// Count Vowels and Consonants - Regular Expressions
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize Scanner and get input string
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
scanner.close();
// Step 2: Convert the string to lowercase to simplify regex patterns
String lowerCaseString = inputString.toLowerCase();
// Step 3: Define regex patterns for vowels and consonants
// [aeiou] matches any vowel
Pattern vowelPattern = Pattern.compile("[aeiou]");
// [a-z&&[^aeiou]] matches any lowercase letter that is not a vowel
Pattern consonantPattern = Pattern.compile("[a-z&&[^aeiou]]");
// Step 4: Count vowels
Matcher vowelMatcher = vowelPattern.matcher(lowerCaseString);
int vowelCount = 0;
while (vowelMatcher.find()) {
vowelCount++;
}
// Step 5: Count consonants
Matcher consonantMatcher = consonantPattern.matcher(lowerCaseString);
int consonantCount = 0;
while (consonantMatcher.find()) {
consonantCount++;
}
// Step 6: Print the results
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
}
}
- Sample Output:
Enter a string: Hello World123! Vowels: 3 Consonants: 7
- Stepwise Explanation:
- The input string is converted to lowercase to handle case-insensitivity easily.
- Two
Patternobjects are created:
-
vowelPattern:[aeiou]matches any single character that is 'a', 'e', 'i', 'o', or 'u'. -
consonantPattern:[a-z&&[^aeiou]]is a character class intersection. It matches any lowercase letter (a-z) AND (&&) any character that is NOT (^) a vowel (aeiou). This efficiently captures all consonants.
- A
Matcherobject is created for each pattern against the lowercase string. - The
while (matcher.find())loop iterates, incrementing the respective count each time a match for the pattern is found in the string. - Finally, the total counts are printed.
Approach 3: Using Java 8 Streams
Java 8 introduced Streams, which provide a functional programming style to process collections of data. This approach can be very concise and expressive.
- Summary: Convert the string to a character stream, filter characters based on vowel/consonant criteria, and count them.
// Count Vowels and Consonants - Java 8 Streams
import java.util.Scanner;
// Main class containing the entry point of the program
public class Main {
public static void main(String[] args) {
// Step 1: Initialize Scanner and get input string
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
scanner.close();
// Step 2: Convert the string to lowercase for easier comparison
String lowerCaseString = inputString.toLowerCase();
// Step 3: Define a string of vowels for quick lookup
String vowels = "aeiou";
// Step 4: Count vowels using streams
long vowelCount = lowerCaseString.chars() // Get an IntStream of character codes
.filter(c -> Character.isLetter(c)) // Filter for alphabetic characters
.filter(c -> vowels.indexOf(c) != -1) // Filter for characters present in 'vowels' string
.count(); // Count the remaining characters
// Step 5: Count consonants using streams
long consonantCount = lowerCaseString.chars() // Get an IntStream of character codes
.filter(c -> Character.isLetter(c)) // Filter for alphabetic characters
.filter(c -> vowels.indexOf(c) == -1) // Filter for characters NOT present in 'vowels' string
.count(); // Count the remaining characters
// Step 6: Print the results
System.out.println("Vowels: " + vowelCount);
System.out.println("Consonants: " + consonantCount);
}
}
- Sample Output:
Enter a string: Hello World123! Vowels: 3 Consonants: 7
- Stepwise Explanation:
- The input string is converted to lowercase to handle case-insensitivity.
- A
vowelsstring is created for efficient checking usingindexOf(). lowerCaseString.chars()returns anIntStream, where each integer represents the ASCII/Unicode value of a character.- The
filter(c -> Character.isLetter(c))step ensures that only alphabetic characters are considered, ignoring numbers, spaces, and symbols. - For vowels,
filter(c -> vowels.indexOf(c) != -1)checks if the character exists within thevowelsstring.indexOf()returns -1 if the character is not found. - For consonants,
filter(c -> vowels.indexOf(c) == -1)checks if the character *does not* exist within thevowelsstring (meaning it's an alphabet but not a vowel). .count()terminates the stream operation and returns the total number of elements that passed all filters.- Finally, the total counts are printed.
Conclusion
Counting vowels and consonants in a string is a foundational problem that demonstrates various string processing techniques in Java. While the basic iteration approach is easy to understand and efficient for most cases, regular expressions offer a powerful pattern-matching syntax, and Java 8 Streams provide a concise, functional way to achieve the same results. Choosing the right approach depends on factors like readability, existing codebase style, and specific performance requirements.
Summary
- Problem: Count vowels (a, e, i, o, u) and consonants in a given string, ignoring non-alphabetic characters.
- Case Sensitivity: Handle by converting the string or characters to lowercase during comparison.
- Basic Iteration: Loop through each character, convert to lowercase, check if it's a letter, then classify as vowel or consonant.
- Regular Expressions: Use
PatternandMatcherwith regex[aeiou]for vowels and[a-z&&[^aeiou]]for consonants. - Java 8 Streams: Convert string to
IntStream, usefilter()forCharacter.isLetter()andString.indexOf()to count.