Hello guys, if you are wondering how to count number of vowels and consonants in a given word in Java then you have come to the right place. In the past, I have shared 100+ data structure questions and more than 75 programming interview questions, and In this article, we will take on a popular programming exercise of counting vowels in a word. You need to write a Java program to count how many vowels in a String, which is entered from the command prompt. It's similar to the program of counting the occurrence of characters in a String, in fact, it's a special case, where you need to count occurrences of all vowels, which includes five characters a, e, i, o and u.
We will also use Scanner to get input from the user to make this this program an interactive exercise as shown in this article. Though I have put down all code inside the main method for quick testing.
If you are asked to write this program as part of your homework or during the interview, better writing a method called public int countVowels(String word) and put the logic of counting vowels there. That's a better coding style than writing everything inside the main method.
By the way, you can also use this logic to count number of consonants in a Java String. What you need to do is first count number of vowels and then subtract those characters from length of String, but remember this will only work if your String contains only alphabetic words, if it contains special character like @, _, | or numbers like 1,2,3 etc, than it will not work.
In that case you need to extend your logic to only count consonants, by extending your switch case to include rest of 21 characters from English alphabets.
You can see that the above String contains 7 vowel characters, highlighted by red font. This method is pretty quick as we are only accessing the array and the using switch to compare it to another character.
In that case you need to extend your logic to only count consonants, by extending your switch case to include rest of 21 characters from English alphabets.
Java Program to count vowels and consonants in String
Here is our complete Java Program to count the number of vowel and consonants in Java:import java.util.Scanner; /** * Java Program to count vowels in a String. It accept a String from command prompt * and count how many vowels it contains. To revise, 5 letters a, e, i, o and u are * known as vowels in English. */ public class VowelCounter { public static void main(String args[]) { System.out.println("Please enter some text"); Scanner reader = new Scanner(System.in); String input = reader.nextLine(); char[] letters = input.toCharArray(); int count = 0; for (char c : letters) { switch (c) { case 'a': case 'e': case 'i': case 'o': case 'u': count++; break; default: // no count increment } } System.out.println("Number of vowels in String [" + input + "] is : " + count); } } Output: Please enter some text How many vowels in this String Number of vowels in String [How many vowels in this String] is : 7
You can see that the above String contains 7 vowel characters, highlighted by red font. This method is pretty quick as we are only accessing the array and the using switch to compare it to another character.
If you notice the switch statement that you will see that we are using fall-through approach, means there is no break for all five cases, as you don't need to put break after every case. it will only increase count at one time, because increment is done at last case statement.
By the way, you can reduce all this code to just few lines using Java 8 Lambda and Stream API as shown below:
Arrays.stream(input.split("")) .filter(character -> "AEIOU".contains(character.toUpperCase())) .count();
Other Java Programming exercise for Practice
- How to check Prime numbers in Java
- Write a Java program to calculate GCD of two numbers
- How to print pyramid pattern in Java
- How to Find Nth Fibonacci Number in Java?
- How to rotate an array in Java?
- How to transpose a Matrix in Java?
- How to print a left triangle star pattern in Java
- How to implement Fibonacci series with caching
- Write a Java program to check Armstrong number in Java
- How to find if a number is palindrome in Java
- Java Program to print Fibonacci Series using Recursion
Thanks for reading this article so far. If you find this question interesting and my solution worth learning then big thank you. Feel free to ask any question or doubt you have in comment section.
import java.util.regex.*;
ReplyDeletepublic class TotalVowelsandConsonants {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "Programming";
int vowel = 0;
int consonents = 0;
char[] charArr = str.toCharArray();
for (char c : charArr) {
if (Pattern.matches("[aeiou]", Character.toString(c)))
vowel++;
else {
consonents++;
}
}
System.out.println(vowel+" "+consonents);
}
}
private static void countVowelAndConsonants(String str) {
ReplyDeleteif( isEmpty(str) ) return ;
int vowelCount = 0;
int consonantsCount = 0;
String vowelStr = new String("aeiouAEIOU");
for( char ch : str.toCharArray() ) {
int unicode = (int)ch;
//First make sure given string has only alphabets, if it has chars other than alphabets skip it.
if( (unicode <= 90 && unicode >= 65 ) || (unicode <= 122 && unicode >= 97 ) ) {
//check for vowels now.
if( vowelStr.contains(ch+"") ) {
vowelCount++;
}
else {
consonantsCount++;
}
}
else {
continue;
}
}
System.out.println("vowelCount==>"+vowelCount);
System.out.println("consonantsCount==>"+consonantsCount);
}
public static boolean isEmpty(String str) {
if( null == str || "".equals(str.trim()) ) {
return true;
}
return false;
}
Good solution !!
DeleteNice.
Delete
ReplyDelete#include
#include
#include
#define VOWEL_CONSONENT_PRESENT 0
#define NO_VOWEL_CONSONENT_PRESENT 1
void TestCase (int, char *);
int ConsonentVowel (int,int,char *);
int main()
{
//Test Case 1
char str1[] = "vibhay kumar";
TestCase(1, str1);
//Test Case 2
char str2[] = " ";
TestCase(2, str2);
//Test Case 3
char str3[] = "140";
TestCase(3, str3);
_getch();
}
void TestCase(int id, char *string)
{
int VowelCount = 0;
int ConsonnentCount = 0;
printf("\n\n\tTEST CASE %d", id);
int ReturnCode = ConsonentVowel(VowelCount, ConsonnentCount, string);
if (ReturnCode == 0)
{
printf("\t\nNumber of consenent count and vowel count are shown above");
}
else
{
printf("\t\nthere are neither consonent nor vowel present in string");
}
}
int ConsonentVowel(int VowelCount, int ConsonentCount, char *string)
{
while (*string)
{
if (*string == 'a' || *string == 'e' || *string == 'i' || *string == 'o' || *string == 'u')
{
VowelCount++;
}
else
{
if (*string != 0 && *string != 9 && *string !=' ' && *string !='\0')
{
ConsonentCount++;
}
}
string++;
}
if (VowelCount > 0 && ConsonentCount > 0)
{
printf("\nNumber of vowels present in string are %d", VowelCount);
printf("\nNumber of consonent present in string are %d", ConsonentCount);
return VOWEL_CONSONENT_PRESENT;
}
else
{
return NO_VOWEL_CONSONENT_PRESENT;
}
}
int count=0;
ReplyDeleteint count1=0;
Scanner sc =new Scanner(System.in);
String in=sc.next();
for(int i=0;i<in.length();i++)
{
if(in.charAt(i)=='a'|| in.charAt(i)=='A'||in.charAt(i)=='e'||in.charAt(i)=='E'|| in.charAt(i)=='i'||in.charAt(i)=='I'||+
in.charAt(i)=='O'||in.charAt(i)=='O'||in.charAt(i)=='U'||in.charAt(i)=='u')
{
count++;
}
else
count1++;
}
System.out.println("Vowels:"+count);
System.out.println("consonants:"+count1);
public static void checkvowels(String str)
ReplyDelete{
int volwel =0;
int cons = 0;
int others = 0;
String vow = "aeiouAEIOU";
for(char ch : str.toCharArray())
{
int asci_val = (int) ch;
if( (asci_val >=65 && asci_val <= 90) || (asci_val >=97 && asci_val <= 122))
{
if(vow.contains(""+ch)) {volwel++;}
else{cons++;}
}
else{others++;}
}
System.out.println(volwel + " " + cons + " " + others);
}
@Unknown, what is the complexity, both time and space of this solution? Can you make it better? faster?
DeleteHow to remove duplicate counting in this program.
ReplyDeleteAny one knows?
@Ashesh: What do you mean duplicate counting ? Here we have to count total number so if its duplicated it will get added.
ReplyDeletePlease elaborate more.
Thanks !
//count number of vowels and consonants in a String
ReplyDeleteprivate void countVowelsConsonants(String s){
String vowels = "aeiou";
int i=0;
int countVowels = 0;
int countCons = 0;
while(i<s.length()){
if(vowels.indexOf(s.charAt(i)) == -1){
countCons++;
}else{
countVowels++;
}
i++;
}
System.out.println("In the string "+s);
System.out.println("Count of vowels :"+countVowels);
System.out.println("Count of consonents :"+countCons);
}
public class CountVowels {
ReplyDeletepublic static void main(String[] args) {
final String stringToCount = "Programming";
final String vowels = "aeiouAEIOU";
int count = 0;
for (char s : vowels.toCharArray()) {
count += stringToCount.length() - stringToCount.replaceAll(String.valueOf(s), "").length();
}
System.out.println(count);
}
}
package nit;
ReplyDeleteimport java.io.*;
public class CountVowelDemo {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
String str;
int vowels = 0, consonents , blanks = 0;
char ch;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a String : ");
str = br.readLine();
for(int i = 0; i < str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
vowels ++;
else if(Character.isWhitespace(ch))
blanks ++;
}
consonents=str.length()-(vowels+blanks);
System.out.println("Vowels : " + vowels);
System.out.println("Digits : " + consonents);
System.out.println("Blanks : " + blanks);
}
}
/*
ReplyDeleteThis is very simple program to count vowels and consonants from given String even String contains any type of characters(i.e. Symbol, digit, alphabet or operator)
*/
import java.util.Scanner;
public class VowelsNConsonantsCounter {
public static void main(String args[]) {
System.out.println("Please enter some text:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
int count1 = 0;
int count2 = 0;
for (int i = 0; i < input.length(); i++) {
if (Character.isAlphabetic(input.charAt(i)))
switch (input.charAt(i)) {
case 'a':
case 'A':
case 'e':
case 'E':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
count1++;
break;
default:
count2++;
}
}
System.out.println("Number of vowels in String [" + input + "] is : " + count1);
System.out.println("Number of Consonants in String [" + input + "] is : " + count2);
}
}
the easiest way to do it!
ReplyDeletepublic class CountVowels {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int counter=0;
System.out.println("Enter text:");
String strText = input.nextLine();
for (int i = 0; i < strText.length(); i++)
{
if(strText.charAt(i)== 'a'){
counter++;
}
else if(strText.charAt(i)== 'e'){
counter++;
}
else if(strText.charAt(i)== 'i'){
counter++;
}
else if(strText.charAt(i)== 'o'){
counter++;
}
else if(strText.charAt(i)== 'u'){
counter++;
}
}
System.out.println("The number of vowels in " + strText + " is " + counter);
}
}
Indeed it's an easiest way but why not use the switch statement instead of block of if-else, that will make it more readable.
Deletepackage simple;
ReplyDeleteimport java.util.Scanner;
public class Vowels {
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.println("Enter string");
String st1= sc.nextLine();
int count=0;
char[] ch= st1.toCharArray();
for(char c:ch){
if (Character.toLowerCase(c)=='a'||Character.toLowerCase(c)=='e'|| Character.toLowerCase(c)=='i'|| Character.toLowerCase(c)=='o'||Character.toLowerCase(c)=='u' ){
count++;
}
}
System.out.printf("No of vowels are %d", count);
}
}
//Also a simple way to count vowel and consonents.
ReplyDeletepublic class CountVowelConsonents {
public static void main(String[] args) {
String str = "abcdefhgijklmnopqrstuvwxrz";
char ch[] = str.toCharArray();
int vowel = 0, conso = 0;
for(char c :ch)
{
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u')
{
vowel++;
}
else
conso++;
}
System.out.println("Number of vowel in "+str+" : "+vowel);
System.out.println("Number of consonent in "+str+" : "+conso);
}
}
What does it mean
Deletechar ch [] = str.tochararray();
And
for(char c :ch)
It first get the character array from string and then loop thorugh it to go over each character. for(char c: ch) is a for loop variation added on Java 5. Also known as for each loop
Deletepublic static Map countVowelsAndConsonants(String input){
ReplyDeleteMap result = new HashMap<>();
int vowelsCounter = 0;
int consonantsCounter =0;
Map vowels = new HashMap(){{
put('a', 'a');
put('e', 'e');
put('i', 'i');
put('o', 'o');
put('u', 'u');
}};
for(Character c : input.toCharArray()){
int unicode = (int) c;
if(unicode >= 97 && unicode <= 122 || unicode >= 65 && unicode <= 90){
if(vowels.get(c) == null){
consonantsCounter++;
}else{
vowelsCounter++;
}
}
}
result.put("vowels", vowelsCounter);
result.put("consonants", consonantsCounter);
return result;
}
import java.util.Scanner;
ReplyDeletepublic class Student8
{
public static void main(String[] args)
{
System.out.print("Enter your String: ");
String str = new Scanner(System.in).nextLine().toLowerCase();
int len = str.length();
int countVowel = 0, constant = 0;
char[] tochar = str.toCharArray();
for (int i = 0; i < len; i++)
{
if (tochar[i] == 'a' || tochar[i] == 'e' || tochar[i] == 'i' || tochar[i] == 'o' || tochar[i] == 'u')
{
countVowel = countVowel + 1;
}
else
{
constant = constant + 1;
}
}
System.out.println("Given string [" + str + "] contains [" + countVowel + "] vowel and [" + constant + "] constant.");
}
}
public static void main(String[] args) {
ReplyDeleteString string = "programming";
String strVowels = "";
String strConsonants = "";
int vowels = 0;
int consonants = 0;
if (!string.equals("")) {
char chars[] = string.toUpperCase().toCharArray();
for (int i = 0; i < chars.length; i++) {
if (chars[i] == 'A' || chars[i] == 'E' || chars[i] == 'I' || chars[i] == 'O' || chars[i] == 'U') {
vowels++;
strVowels = strVowels+" " + chars[i];
} else if (Pattern.compile("[0-9]").matcher(Character.toString(chars[i])).find()) {
System.out.println("String contains Numbers");
return;
} else {
consonants++;
strConsonants = strConsonants+" " + chars[i];
}
}
System.out.println(vowels +" Vowels in String :-" + string + " those are " + strVowels);
System.out.println(consonants +" Consonants in String :-" + string + "those are " + strConsonants);
} else {
System.out.println("Please pass some string value to find vowels and consonants");
}
}
Enough of this Loops,
ReplyDeletehere's a simple code for this simple problem.
String lettersOnly = input.replaceAll("(?i)[^a-z]+", "");
String consonentsOnly = lettersOnly.replaceAll("(?i)[aeiou]+", "");
int consonentCount = consonentsOnly.length();
int vowelCount = lettersOnly.length() - consonentCount;
System.out.printf("Volwes %d, Consonents %d%n", vowelCount, consonentCount);
I am a Frontend developer. So my solution is in Javascript:
ReplyDeletefunction vowel(str) {
var count = 0;
debugger
var arr = ["a", "e", "i", "o", "u"];
for(var i = 0; i <= str.length - 1; i++) {
if(arr.indexOf(str[i]) !== -1) {
count++;
}
}
return count;
}
vowel("Hello Kanchan") // 4
static int countNumberOfVowels(String input) {
ReplyDeleteList vowelsList = Arrays.asList('a', 'e', 'i', 'o', 'u');
int count = 0;
for (Character character : input.toCharArray()) {
if (vowelsList.contains(character))
count++;
}
return count;
}
ReplyDeletepublic class MyClass {
public static void main(String args[]) {
String vowelArr ="aeiou";
int concount=0, vowelcount=0;
String str ="bcdfghjklmnpqrstvwxyz";
char[] arr= str.toLowerCase().toCharArray();
for(int i=0; i< arr.length; i++){
if(vowelArr.contains(arr[i]+""))
vowelcount++;
else
concount++;
}
System.out.println("VowleCount is : "+ vowelcount + " and Consonants count is : " + concount);
}
}
Hi, I need help. This is the task: to type strings from the keyboard until you type "end" and print ONLY STRINGS THAT HAVE THE SAME NUMBER OF VOWELS AND CONSONANTS.
ReplyDeleteHello Anonymous, what help you need? where did you stuck? Can you post your code? If you are looking for ideas, you can read input in Java using Scanner class and then use the logic here to count vowels and consonants. You can also split the string on space before counting.
Delete