Java Program to count the total number of vowels and consonants in a string
In this program, our task is to count the total number of vowels and consonants present in the given string. As we know that, the characters a, e, i, o, u are known as vowels in the English alphabet. Any character other than that is known as the consonant.
To solve this problem, First of all, we need to convert every upper-case character in the string to lower-case so that the comparisons can be done with the lower-case vowels only not upper-case vowels, i.e.(A, E, I, O, U). Then, we have to traverse the string using a for or while loop and match each character with all the vowels, i.e., a, e, i, o, u. If the match is found, increase the value of count by 1 otherwise continue with the normal flow of the program. The algorithm of the program is given below.
string
this is a comman name
Class
Program
class vowel {
public static void main(String[] args)
//declare String
String str1="this is a comman name";
int vCount = 0, Ccount = 0;
//Converting both the string to lower case.
str1 = str1.toLowerCase();
for (int i=0;i< str.length();i++)
{
if(str.charAt(i)=='a' || str.charAt(i)=='e' || str.charAt(i)=='u' || str.charAt(i)=='o' || str.charAt(i)=='i' )
{
vcount++;
}
else if (str.charAt(i)>='a' && str.charAt(i) < ='z')
{
Ccount++;
}
System.out.println("total vowel is = "+ vcount);
System.out.println("constants is =" + Ccount);
}
}
output
total vowel is = 7
constants is =10
Theory:-
In this problem to firstly know what is vowels and constants .we have to five alphabate 'a' 'e' 'u' 'i' 'o' is the vowels . renaming alphabate are the constants expect black space and syball are not the constants.
To calculate of given string to how many vowels and constants are the present in string.
we are fristly to given string convert to either uppercase or lowercase .then use for loop to strating 0 and end to string length. in loop to specific word compair to vowels is use ChartAt() method in string. if condition is true then increase count of vowels. if condition is false then count constants of the given string.
No comments:
Post a Comment