Java 8 – Count and print number of Vowels and Consonants in a String

In this article, we will learn how to count number of vowels and consonants in a String ignoring space characters

Count Vowels and Consonants :

  1. Using Java 8String.char() and Stream.filter() and Stream.count() methods
  2. Using String.toCharArray() method
  3. Using String.charAt(index) method

1. Using Java 8 – String.char() and Stream.filter() and Stream.count() methods

  • First, we will check whether input String is not null otherwise throw new IllegalArgumentException to the invoking method
  • Remove space characters if any using String.replaceAll(old, new)
  • After necessary null check and removing space characters, get Stream using Stream.chars() method
    • Vowels – Filter out vowel characters using Stream.filter() method and count them using count() method
    • Consonants – Filter out non-vowel characters using Stream.filter() method and count them using count() method
  • Finally, we will print vowel & consonants count to the console

CountVowelsAndConsonantsUsingJava8.java

package in.bench.resources.string.operation;

public class CountVowelsAndConsonantsUsingJava8 {

	// global variables
	private static long VOWELS = 0;
	private static long CONSONANTS = 0;


	// main() method
	public static void main(String[] args) {

		// test string
		String str = "BenchResourcesNet has very useful examples and tips on Java";


		// print to console - original String
		System.out.println("Input String :- \n" + str);


		// call method
		countVowelsAndConsonants(str);


		// print to console
		System.out.println("\nVowel count is = " + VOWELS);
		System.out.println("Consonant count is = " + CONSONANTS);
	}


	/**
	 * this method is used to count vowels & consonants using Java 8 Stream
	 * 
	 * @param str
	 */
	public static void countVowelsAndConsonants(String str) {

		// check whether input string is not null
		if(null == str) {
			throw new IllegalArgumentException("Input String cannot be null");
		}


		// replace all spaces - ignore space characters
		str = str.replaceAll(" ", "");


		// count vowels
		VOWELS = str // original source or string
				.chars() // get character stream
				.filter(ch -> (
						'a' == ch || 'e' == ch || 'i' == ch || 'o' == ch || 'u' == ch || 
						'A' == ch || 'E' == ch || 'I' == ch || 'O' == ch || 'U' == ch)
						) // filter out vowels
				.count(); // count vowels


		// count consonants
		CONSONANTS = str // original source or string
				.chars() // get character stream
				.filter(ch -> (
						ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')
						) // check whether it is in range
				.filter(ch -> (
						'a' != ch && 'e' != ch && 'i' != ch && 'o' != ch && 'u' != ch && 
						'A' != ch && 'E' != ch && 'I' != ch && 'O' != ch && 'U' != ch)
						) // filter out non-vowels
				.count(); // count consonants
	}
}

Output:

Input String :- 
BenchResourcesNet has very useful examples and tips on Java

Vowel count is = 19
Consonant count is = 32

2. Using String.toCharArray() method

  • First, we will check whether input String is not null otherwise throw new IllegalArgumentException to the invoking method
  • Remove space characters if any using String.replaceAll(old, new) and convert to char[] array using String.toCharArray() method
  • Iterate through char[] array, reading one character at a time,
    • Vowels – Check if the character in question is (a, e, i, o, u) or (A, E, I, O, U) then increment vowel count by 1
    • Consonants – Check if the character in question is not (a, e, i, o, u) or (A, E, I, O, U) and falls within the range of (a-z) or (A-Z) then increment consonant count by 1
  • Finally, we will print vowel & consonant count to the console

CountVowelsAndConsonantsUsingToCharArray.java

package in.bench.resources.string.operation;

public class CountVowelsAndConsonantsUsingToCharArray {

	// global variables
	private static int VOWELS = 0;
	private static int CONSONANTS = 0;


	// main() method
	public static void main(String[] args) {

		// test string
		String str = "BenchResourcesNet has very useful examples and tips on Java";


		// print to console - original String
		System.out.println("Input String :- \n" + str);


		// call method
		countVowelsAndConsonants(str);


		// print to console
		System.out.println("\nVowel count is = " + VOWELS);
		System.out.println("Consonant count is = " + CONSONANTS);
	}


	/**
	 * this method is used to count vowels & consonants
	 * 
	 * @param str
	 */
	public static void countVowelsAndConsonants(String str) {

		// check whether input string is not null
		if(null == str) {
			throw new IllegalArgumentException("Input String cannot be null");
		}


		// replace all spaces & convert to character arrays - ignore space characters
		char[] chArray = str.replaceAll(" ", "").toCharArray();


		// iterate String characters and count vowels & consonants
		for(int index = 0; index < chArray.length; index++) {

			// read one character at a time
			char ch = chArray[index];

			// check for vowels
			if('a' == ch || 'e' == ch || 'i' == ch || 'o' == ch || 'u' == ch
					|| 'A' == ch || 'E' == ch || 'I' == ch || 'O' == ch || 'U' == ch) {

				// increment count by 1
				VOWELS++;
			}
			else if((ch >= 'a' && ch <= 'z') ||
					(ch >= 'A' && ch <= 'Z')) { // check for consonants

				// increment count by 1
				CONSONANTS++;
			}
			else {
				System.out.println("\n" + ch + " isn't Vowel or Consonant");
			}
		}
	}
}

Output:

Input String :- 
BenchResourcesNet has very useful examples and tips on Java

Vowel count is = 19
Consonant count is = 32

3. Using String.charAt(index) method

  • First, we will check whether input String is not null otherwise throw new IllegalArgumentException to the invoking method
  • Remove space characters if any using String.replaceAll(old, new)
  • Iterate using for-loop starting with 0 till length of the input String and get single character from the given String passing index-position using String.charAt(index)
    • Vowels – Check if the character in question is (a, e, i, o, u) or (A, E, I, O, U) then increment vowel count by 1
    • Consonants – Check if the character in question is not (a, e, i, o, u) or (A, E, I, O, U) and falls within the range of (a-z) or (A-Z) then increment consonant count by 1
  • Finally, we will print vowel & consonant count to the console

CountVowelsAndConsonantsInJava.java

package in.bench.resources.string.operation;

public class CountVowelsAndConsonantsInJava {

	// global variables
	private static int VOWELS = 0;
	private static int CONSONANTS = 0;


	// main() method
	public static void main(String[] args) {

		// test string
		String str = "BenchResourcesNet has very useful examples and tips on Java";


		// print to console - original String
		System.out.println("Input String :- \n" + str);


		// call method
		countVowelsAndConsonants(str);


		// print to console
		System.out.println("\nVowel count is = " + VOWELS);
		System.out.println("Consonant count is = " + CONSONANTS);
	}


	/**
	 * this method is used to count vowels & consonants
	 * 
	 * @param str
	 */
	public static void countVowelsAndConsonants(String str) {

		// check whether input string is not null
		if(null == str) {
			throw new IllegalArgumentException("Input String cannot be null");
		}


		// replace all spaces - ignore space characters
		str = str.replaceAll(" ", "");


		// iterate String characters and count vowels & consonants
		for(int index = 0; index < str.length(); index++) {

			// read one character at a time
			char ch = str.charAt(index);

			// check for vowels
			if('a' == ch || 'e' == ch || 'i' == ch || 'o' == ch || 'u' == ch
					|| 'A' == ch || 'E' == ch || 'I' == ch || 'O' == ch || 'U' == ch) {

				// increment vowel count by 1
				VOWELS++;
			}
			else if((ch >= 'a' && ch <= 'z') ||
					(ch >= 'A' && ch <= 'Z')) { // check for consonants

				// increment consonant count by 1
				CONSONANTS++;
			}
			else {
				System.out.println("\n" + ch + " isn't Vowel or Consonant");
			}
		}
	}
}

Output:

Input String :- 
BenchResourcesNet has very useful examples and tips on Java

Vowel count is = 19
Consonant count is = 32

References:

Happy Coding !!
Happy Learning !!

Java 8 – How to check whether given String contains only Alphabets or Letters ?
Java - Swapping 2 Strings without Third variable