-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

Saturday, July 18, 2020

Java Program To Count Vowels and Consonants in a String

  • July 18, 2020
  • by

Java Program To Count Vowels and Consonants in a String

In this Java Program, we count the vowels and consonants in a string.

The alphabet contains 26 letters, among them A, E, I,  O, U (small and upper case) are known as vowels while the remaining 21 letters are known as consonants.  

Logic : String str = "Itengineer8995";
             int vcount = 0, ccount = 0;

             str = str.toLowerCase();
             for(int i = 0; i < str.length(); i++)
             {
                char ch = str.charAt(i);
                if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                  {
                      vcount++;
                   }
                else if((ch >= 'a' && ch <= 'z'))
                        {
                            ccount++;
                        }
                }

Step 1 : Create variable str and store the string in it.

Step 2 : Create and initialize variable vcount to 0 and ccount to 0.

Step 3 : Convert all the chars to lowercase by using toLowerCase method of the String class and store it in the variable str.

Step 4 : Apply for loop where i is equal to 0, i should be less than length of the string and increment i.

Step 5 : Create variable char ch and store the string at char position i.

Step 6 : apply if else if statement. If ch is equal to a or ch is equal to e or ch is equal to i or ch is equal to o or ch is equal to u then increment the vcount. else if  ch is greater than or equal to a and ch is less than or equal to z then increment ccount.

Step 7 : Print number of vowels and consonants.

Program :

public class VowelConsonant2 

    {
        public static void main(String[] args)
        {
            String str = "Itengineer8995";
            int vcount = 0, ccount = 0;
            
            //converting all the chars to lowercase
            str = str.toLowerCase();
            for(int i = 0; i < str.length(); i++)
            {
                char ch = str.charAt(i);
                if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                {
                    vcount++;
                }
                else if((ch >= 'a' && ch <= 'z'))
                        {
                            ccount++;
                        }
            }
            System.out.println("Number of Vowels :" +vcount);
            System.out.println("Number of Consonants :" +ccount);        
        }


Output :

Number of Vowels :5
Number of Consonants :5

For execution of the same do visit my YouTube Channel :





A blog full of codes of various languages like Java, .net, C, C++ etc with their outputs and some other IT stuff.

0 comments:

Post a Comment

ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages