Reputation: 603
Can anyone please tell me what I am doing wrong in my code? I need to count the number of vowel occurances in a string using recursion. The function isVowels checks if the character is a vowel and it works. But this code below doesn't work...
function countVowels(str) {
var length = str.length;
if (length == 0) {
return 0;
}
if (isVowel(str.charAt(length)) == false) {
return countVowels(str.substring(0, length - 1));
}
return 1 + countVowels(str.substring(0, length - 1));
}
Upvotes: 0
Views: 2071
Reputation: 664195
Characters in a string are - just like elements in an array - zero-indexed. You will need to use .charAt(length-1)
, or you're getting the character after the end of the string (which yields the empty string). This should do it:
function countVowels(str) {
var length = str.length;
if (length == 0) {
return 0;
}
if (isVowel(str.charAt(length - 1)) == false) {
return countVowels(str.substring(0, length - 1));
}
return 1 + countVowels(str.substring(0, length - 1));
}
However, you could simplify this by not calling the recursive part twice, and counting from the front:
function countVowels(str) {
if (str.length == 0)
return 0;
return (isVowel(str.charAt(0)) ? 1 : 0) + countVowels(str.slice(1));
}
Upvotes: 4