Using Recursion & substring to count a's in a string phrase

Mar 21, 2013 at 3:29pm
This is a college assignment that I'm stuck on.
Write a recursive function that counts the number of a's in a string. Your program should include a driver that asks the user for a string, calls the recursive function, and outputs the number of a's it found in the string input by the user.


This is what I have:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int countA(string, string);

int main()
{
	string userInput;
	string a = "a";

	// Explain purpose of program to the user
	cout <<"Purpose of this program is to count" << endl;
	cout <<"the number of a's in a phrase inputted by the user\n" << endl;

	//  Asks the user for a string
	cout << "Please enter a short phrase: ";
	cin >> userInput;
	// Call countA() in order to count the number of a's in the phrase

	cout <<"The number of a's in the phrase is: " << countA(userInput, a) << endl;
	system("PAUSE");
	return 0;
}

int countA(string input, string a, )
{
	int count = 0;
	if(input != a)
	{
		return count;
	}
	else
	{
		count++;
		return count + countA(input.substr(1), a); 
                //Have to use substring
	}		
}


I get 0 for my output. I think it's because I keep reinitializing count to 0 each time I go through but I'm not 100% sure. This is my first time with recursion and I understand the concept of it but I don't feel that I'm implementing it correctly here. Friendly advice appreciated.
Mar 21, 2013 at 3:33pm
You always get 0 due to the following snip of the function code

1
2
3
4
	if(input != a)
	{
		return count;
	}


It is obvious that the whole entered string is not equal to one symbol 'a' except the case when single 'a' was entered.:).
Last edited on Mar 21, 2013 at 3:48pm
Mar 21, 2013 at 3:41pm
Yeah I see that now. I just gotta figure out how to compare each letter in the string with the letter a.
Mar 21, 2013 at 3:47pm
If you need to count only character 'a' then it is better to declare it as

const char c = 'a';

instead of

string a = "a";

and compare each character in string userInput with this character. For example

if ( userInput[0] == c )
Mar 21, 2013 at 8:54pm
I'm a beginner at C++ but to me it looks like you are also, as you said, reinitializing count to 0 every time the function is run. Shouldn't

int count = 0;

be

static int count = 0;
?

I could be wrong. I haven't built a recursive function yet so i'm having trouble grasping how the return count + countA statement is working.
Topic archived. No new replies allowed.