Given a String count the total number of vowels and consonants in this given string. Assuming String may contain only special characters, or white spaces, or a combination of all. The idea is to iterate the string and checks if that character is present in the reference string or not. If a character is present in the reference increment number of vowels by 1, otherwise, increment the number of consonants by 1.
Example:
Input : String = "GeeksforGeeks"
Output: Number of Vowels = 5
Number of Consonants = 8
Input : String = "Alice"
Output: Number of Vowels = 3
Number of Consonants = 2
Approach:
- Create two variables vow and cons and initialize them with 0.
- Start string traversing.
- If i’th character is vowel then increment in vow variable by 1.
- Else if the character is consonant then increment in cons variable by 1.
Example
Java
import java.util.*;
class GFG {
public static void count(String str)
{
int vow = 0 , con = 0 ;
String ref = "aeiouAEIOU" ;
for ( int i = 0 ; i < str.length(); i++) {
if ((str.charAt(i) >= 'A'
&& str.charAt(i) <= 'Z' )
|| (str.charAt(i) >= 'a'
&& str.charAt(i) <= 'z' )) {
if (ref.indexOf(str.charAt(i)) != - 1 )
vow++;
else
con++;
}
}
System.out.println( "Number of Vowels = " + vow
+ "\nNumber of Consonants = "
+ con);
}
public static void main(String[] args)
{
String str = "#GeeksforGeeks" ;
count(str);
}
}
|
Output
Number of Vowels = 5
Number of Consonants = 8
Time Complexity: O(n²) here, n is the length of the string.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
01 Feb, 2023
Like Article
Save Article