Skip to content
Related Articles

Related Articles

Java Program to Count the Total Number of Vowels and Consonants in a String
  • Difficulty Level : Basic
  • Last Updated : 24 Nov, 2020

Given a String count the total number of vowels and consonants in this given string. Assuming String may contain only special characters, or white spaces, or a combination of all. The idea is to iterate the string and checks if that character is present in the reference string or not. If a character is present in the reference increment number of vowels by 1, otherwise, increment the number of consonants by 1.

Example:

Input : String = "GeeksforGeeks"
Output: Number of Vowels = 5
        Number of Consonants = 8

Input : String = "Alice"
Output: Number of Vowels = 3
        Number of Consonants = 2

Approach:

  1. Create two variables vow and cons and initialize them with 0.
  2. Start string traversing.
  3. If i’th character is vowel then increment in vow variable by 1.
  4. Else if the character is consonant then increment in cons variable by 1.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java Program to count the total number
// of vowels and consonants in a string
import java.util.*;
  
public class GFG {
    // prints number of vowels and consonants //
    public static void count(String str)
    {
        int vow = 0, con = 0;
        // reference String which contains all the vowels //
        String ref = "aeiouAEIOU";
        for (int i = 0; i < str.length(); i++) {
            // Check for any special characters present in
            // the given string
            if ((str.charAt(i) >= 'A'
                 && str.charAt(i) <= 'Z')
                || (str.charAt(i) >= 'a'
                    && str.charAt(i) <= 'z')) {
                if (ref.indexOf(str.charAt(i)) != -1)
                    vow++;
                else
                    con++;
            }
        }
        System.out.println("Number of Vowels = " + vow
                           + "\nNumber of Consonants = "
                           + con);
    }
  
    public static void main(String[] args)
    {
        String str = "#GeeksforGeeks";
        count(str);
    }
}

chevron_right


Output

Number of Vowels = 5
Number of Consonants = 8

Time Complexity: O(n) here, n is the length of the string.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :