- Given String in java.
- We would like to count number of vowels & consonants
- In English there are 26 alphabets (ignoring case)
- There are five vowels in English a, e, i, o, u and rest 21 alphabets are consonants.
Examples: Vowels & Consonants in English
Example : Input String = "Hello Java" Number of vowels in given string are 4 Number of consonants are 6 |
Algorithm: count vowels & consonants of String in Java:
- User enter the input string.
- Convert input string to lowercase
- Iterate through input string:
- Check given character is vowel
- If character is vowel then increment vowel count.
- Check given character is consonant if chInput >= ‘a’ && chInput <= ‘z’
- If character is consonant then increment consonant count.
- Check given character is vowel
- Print number of vowels & consonants.
Program: count number of vowels & consonants in Java
package org.learn.beginner; import java.util.Scanner; public class CountVowelAndConsonant { public static void main(String[] args) { String VOWEL = "aeiou" ; int iVowels = 0 , iConsonants = 0 ; try (Scanner scanner = new Scanner(System.in)) { System.out.print( "Enter input string : " ); String input = scanner.nextLine().toLowerCase(); for ( char chInput : input.toCharArray()) { String strChar = String.valueOf(chInput); if (VOWEL.contains(strChar)) { iVowels++; } else if (chInput >= 'a' && chInput <= 'z' ) { iConsonants++; } } System.out.printf( "Vowel Count: %d \n" , iVowels); System.out.printf( "Consonant Count: %d " ,iConsonants); } } } |
Output: print number of vowel & consonant of string in java
Enter input string : Hello Java Vowel Count: 4 Consonant Count: 5 |