Problem with finding vowels with recursion

bool containsVowel(string blah){
if (blah == ""){
return false;
} else if (blah[0] == 'a' || blah[0] == 'e' || blah[0] == 'i' || blah[0] == 'o' || blah[0] == 'u' || blah[0] == 'A' || blah[0] == 'E' || blah[0] == 'I' || blah[0] == 'O' || blah[0] == 'U'){
return true;
} else{
containsVowel(blah.substr(1));
}
}

There is the code, for some reason it always returns true unless the string is empty to begin with.
Erm... I am not sure if that is legal.. Why not use string::find? http://www.cplusplus.com/reference/string/string/find/
You doesn't return anything in the else part.
Last edited on
closed account (o1vk4iN6)
Well rather than passing a string you could just pass a const char*.

1
2
3
4
5
6
7
8

bool hasVowel( const char* str )
{
     if(str == '\0') return false; // base case, end of string... no vowels
     else if( *str == 'a' /*|| ... etc */ ) return true; // return true if has vowels...
     else return hasVowel( str + 1 );
}


The problem is rather easy to solve, you don't need a recursive function which will make it relatively slower than a while loop, or using an already existing function in std::string.

Not to mention you are making a copy of "blah" each time the function is called which is rather inefficient.
Last edited on
I am using recursion because this is an exercise in a class. I am fairly certain that using the [] is legal, at least my professor said it was. I know that there are much easier ways of doing this, but this is the way I must do it. I am merely asking why it always returns true except when the string is empty. Just as an explanation, the function checks the first letter of the string every time it is called and each time it is called it is passed the previous string minus the first letter. If a vowel is found, true is returned, and if the end is reached and the function is passed an empty string, false is returned.
closed account (o1vk4iN6)
Peter87 wrote:
You doesn't return anything in the else part.


This.

1
2
3
4
5
6
7
8
9
bool containsVowel(string blah){
  if (blah == ""){
    return false;
  } else if (blah[0] == 'a' /*...*/){
    return true;
  } else{
    containsVowel(blah.substr(1)); // undefined behavior, no return statement for this case
  }
}
Last edited on
Thank you, I see now. I just had to have "return", before the function call.
Topic archived. No new replies allowed.