Java Program to find total Vowel, Consonant and words in a String

Java Program to find total Vowel, Consonant and words in a String

Java Program to find total Vowel, Consonant, and words in a String

There are five vowels (a, e, I, o, u) in the English language and rest are consonants among 26 letters of the English alphabet.  

In the following program, the total vowels, total consonants, and total words are calculated. We have built the program in the following steps.

Step 1: String st taken

Step 2: Calculate the length of the String

Step 3: Start a for loop and execute till its length one by one

Step 4: Pick one character at a time with ch = st.charAt(i); and pass to switch(ch)

Step 5: check with the case the vowels and count counters of each vowel variable if find

Step 6: After then calculate the consonants with the formula

                Consonants = length of String - (total vowels + space)

Step 7: Print individual vowels, consonants, and total words.

 

public class StringEx1

{

    public static void main(String args[])

    {

        String st="Education is must for all";

        char ch;

        int i, l, c=0,sp=0, con,v1, v2, v3, v4, v5;

        v1 = v2 = v3 = v4 = v5 =0;

        l=st.length();

        for(i=0;i<l;i++)

        {

            ch=st.charAt(i);

            switch(ch)

            {

                case 'A':

                case 'a':

                v1++;       // vowel a count

                break;

                case 'E':

                case 'e':

                v2++;       // vowel e count

                break;

                case 'I':

                case 'i':

                v3++;       // vowel i count

                break;

                case 'O':

                case 'o':

                v4++;       // vowel o count

                break;

                case 'U':

                case 'u':

                v5++;       // vowel u count

                break;

            }

            // Calculate total Space for count words

            if(ch==' ')

                sp++;

        }

// consonents = length of String - (total vowels + space)

        con = l - (v1 + v2 + v3 + v4 + v5 + sp);

        System.out.println("Total String Length = " + l);

        System.out.println("Total Vowel A= " +v1);

        System.out.println("Total Vowel E= " +v2);

        System.out.println("Total Vowel I= " +v3);

        System.out.println("Total Vowel O= " +v4);

        System.out.println("Total Vowel U= " +v5);

        System.out.println("Total Words = " +(sp+1)); // total space plus 1

        System.out.println("Total Consonants = "+ con);    }

}

Output

Total String Length = 25

Total Vowel A= 2

Total Vowel E= 1

Total Vowel I= 2

Total Vowel O= 2

Total Vowel U= 2

Total Words = 5

Total Consonants = 12

Java program


 


SHARE THIS
Previous Post
Next Post