1.

Write a program in Java to count the total number of vowels and consonants in a String. The string can contain all the alphanumeric and other special characters as well. However, only the lowercase English alphabets are allowed in the String.

Answer»

We just have to traverse the string. If we get any vowel (a,e,i,o,u), we increment the variable corresponding to the vowel count and if we get a consonant, we increment the variable corresponding to the consonant count. 

Java Code to Count Vowels and Consonants in a String

import java.util.*;
class Main {

public static boolean isVowel(char ch) {
if(ch == 'a' || ch =='e' || ch =='i' || ch =='o' || ch =='u')
return true;

return false;
}

public static void main(String args[]) {
// Your code goes here
Scanner scn = new Scanner(System.in);
String str = scn.nextLine();

int vowelCount = 0;
int consCount = 0;

for(int i=0;i<str.length();i++) {
char ch = str.charAt(i);
if(isVowel(ch) == true) vowelCount++;
else if(ch >='a' && ch<='z' && isVowel(ch) == false) consCount++;
}

System.out.println("Number of vowels are: " + vowelCount);
System.out.println("Number of consonants are: " + consCount);
System.out.println("Number of other characters are: " + (int)(str.length() - vowelCount -consCount));
}
}

Sample Output

Input: ae#zyu*

Output:
The number of vowels is: 3
The number of consonants is: 2
The number of other characters is: 2


  • Corner Cases, You Might Miss: In order to check whether a character is a vowel or not, we have a function. However, it is not right to say that if it is not a vowel then it will be a consonant as it can also be any other character. So, we have to make sure that it is an alphabet and then make sure that it is not a vowel. The same is done in the code.


  • Time Complexity: O(N) where N is the length of the input string as we have to traverse the entire string once.


  • Auxiliary Space: O(1) as we have not used any extra space.




Discussion

No Comment Found