Tuesday, June 7, 2022

[Solved] How to count Vowels and Consonants in Java String Word? Example

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.




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. 

[Solved] How to count Vowels and Consonants in Java String Word? Example



Java Program to count Vowels and Consonants in a word using JavaIf 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();

How to count vowel and consonants in Java 8 using lambda and stream


That's all folks on this programming exercise to count Vowel and consonants in Java.  It's interesting to count number of vowels or consonants in Java String, and you can do it differently as well. If you are keen to do more programming exercise, try to come out with a different solution and then compare that with this solution.


Other Java Programming exercise for Practice

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. 

29 comments:

  1. import java.util.regex.*;

    public 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);
    }


    }

    ReplyDelete
  2. private static void countVowelAndConsonants(String str) {
    if( 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;

    }

    ReplyDelete

  3. #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;
    }
    }

    ReplyDelete
  4. rajashekhar baligarJune 16, 2016 at 7:06 AM

    int count=0;
    int 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);

    ReplyDelete
  5. public static void checkvowels(String str)
    {
    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);
    }

    ReplyDelete
    Replies
    1. @Unknown, what is the complexity, both time and space of this solution? Can you make it better? faster?

      Delete
  6. How to remove duplicate counting in this program.
    Any one knows?

    ReplyDelete
  7. @Ashesh: What do you mean duplicate counting ? Here we have to count total number so if its duplicated it will get added.
    Please elaborate more.

    Thanks !

    ReplyDelete
  8. //count number of vowels and consonants in a String
    private 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);
    }

    ReplyDelete
  9. public class CountVowels {
    public 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);
    }

    }

    ReplyDelete
  10. package nit;
    import 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);

    }

    }

    ReplyDelete
  11. /*
    This 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);
    }
    }

    ReplyDelete
  12. the easiest way to do it!

    public 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);

    }
    }

    ReplyDelete
    Replies
    1. 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.

      Delete
  13. package simple;

    import 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);
    }
    }

    ReplyDelete
  14. //Also a simple way to count vowel and consonents.

    public 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);

    }
    }

    ReplyDelete
    Replies
    1. What does it mean
      char ch [] = str.tochararray();
      And
      for(char c :ch)

      Delete
    2. 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

      Delete
  15. public static Map countVowelsAndConsonants(String input){
    Map 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;
    }

    ReplyDelete
  16. import java.util.Scanner;

    public 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.");
    }
    }

    ReplyDelete
  17. public static void main(String[] args) {
    String 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");
    }

    }

    ReplyDelete
  18. Enough of this Loops,
    here'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);

    ReplyDelete
  19. I am a Frontend developer. So my solution is in Javascript:

    function 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

    ReplyDelete
  20. static int countNumberOfVowels(String input) {

    List vowelsList = Arrays.asList('a', 'e', 'i', 'o', 'u');
    int count = 0;

    for (Character character : input.toCharArray()) {
    if (vowelsList.contains(character))
    count++;

    }
    return count;
    }

    ReplyDelete

  21. public 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);
    }
    }

    ReplyDelete
  22. 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.

    ReplyDelete
    Replies
    1. Hello 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

Feel free to comment, ask questions if you have any doubt.