Count number of vowels in string in java
- In java, we can get total number of vowels in string and also get total count of each vowel in given string by using for loop and switch like below:
package Sample;
public class FindVowels {
public static void main(String[] args) {
String str = "keeplearning";
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {
count++;
}
}
System.out.println("Number of vowels in string=" + count);
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 'a':
aCount++;
break;
case 'e':
eCount++;
break;
case 'i':
iCount++;
break;
case 'o':
oCount++;
break;
case 'u':
uCount++;
break;
}
}
System.out.println("Number of vowel a count in string=" + aCount);
System.out.println("Number of vowel e count in string=" + eCount);
System.out.println("Number of vowel i count in string=" + iCount);
System.out.println("Number of vowel o count in string=" + oCount);
System.out.println("Number of vowel u count in string=" + uCount);
}
}
get number of vowels in string |
No comments:
Post a Comment
Please comment below to feedback or ask questions.