Example: Program to count vowels, consonants, digits, and spaces
Output
Vowels: 7 Consonants: 11 Digits: 2 White spaces: 3
In the above example, we've 4 conditions for each of the checks.
- The first
ifcondition is to check whether the character is a vowel or not. - The
else ifcondition followingifis to check whether the character is a consonant or not. This condition is checked only when theifcondition is false. - The second
else ifis to check whether the character is between 0 to 9 or not. - Finally, the last condition is to check whether the character is a space character or not.
For this, we've lowercased the line using toLowerCase(). This is an optimization done not to check for capitalized A to Z and vowels.
We've used length() function to know the length of the string and charAt() to get the character at the given index (position).