CC-16 : Count vowels in input String.
Description:
Given input String str, find and return the count of vowels in the String.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| The input string is: asz-123.reader | Count of vowels: 4 |
| The input string is: Buy123 | Count of vowels: 1 |
| The input string is: ABC | Count of vowels: 1 |
Pseudocode:
| The java method should accept following input parameters: str (String). |
| Initialize char array chars=str.toCharArray(). |
| Initialize int variable vCnt=0, we will use this variable to count number of vowels in str. |
| Iterate through chars using for loop using idx as loop variable, starting from index 0 and incrementing idx till we reach chars.length-1:
If chars[idx] is equal to any of the following a, e, i ,o, u, A, E, I, O, U then :
Increment vCnt by 1.
|
| At the end of above loop, vCnt contains the sum of the vowels in str. Return vCnt. |
Code:
public int stringCountVowels(String str) {
char[] chars=str.toCharArray();
int vCnt=0;
for (int idx=0; idx < chars.length; idx++) {
if (chars[idx]=='a'||chars[idx]=='e'||
chars[idx]=='i'||chars[idx]=='o'||chars[idx]=='u'||
chars[idx]=='A'||chars[idx]=='E'||
chars[idx]=='I'||chars[idx]=='O'||chars[idx]=='U') {
vCnt++;
}
}
return vCnt;
}
public int stringCountVowelsWithAPI(String str) {
int vCnt=0;
String vowels="aeiouAEIOU";
for (int idx=0; idx < str.length(); idx++) {
if (vowels.contains(str.subSequence(idx, idx+1))) {
vCnt++;
}
}
return vCnt;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |