recursively check if a string contains a vowel

I am trying to write a recursive function to check if a string contains a vowel..
Here is my code but it does not return the correct value, can anyone help me please:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <string>
using namespace std;

string s = "aeiouAEIOU";
bool containsVowel(string str){
	if(s.find(str.at(0)) == string::npos)
		return false;
	else
		return containsVowel(str.substr(1)); // I think there is something wrong with this line here, but can't figure out how to fix it... I need to put "true" somewhere in this line here right?
}
Last edited on
Try the following code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <iomanip>
#include <string>


const std::string s = "aeiouAEIOU";
bool containsVowel( std::string str)
{
	if ( str.size() == 0 ) return ( false );
	return ( ( s.find( str[0] ) == std::string::npos )
		       ? containsVowel( str.substr( 1 ) )
			   : true );
}


int main()
{
	std::cout << std::boolalpha << containsVowel( "bcdfg" ) << std::endl;
	std::cout << std::boolalpha << containsVowel( "bcdAfg" ) << std::endl;
}
Thank you so much, your code works perfectly!
My code throws an out-of-bound exception, I forgot to check the base case..
Last edited on
Topic archived. No new replies allowed.