Function that counts the number of times a specific character appears in a string

I have an assignment for my CS class.

It is the following:

*
* complete the function:
*
* timesFound(string searchIn, char searchFor);
*
* The function should return the number of times the
* character searchFor appears in the string searchIn.
*
*/
int timesFound(string searchIn, char searchFor)
{
}

int main()
{
string textLine;
char findThis, response = 'y';
bool running = true;

while (running)
{
cout << "Please enter a line of text: ";
getline(cin, textLine);
cout << "Please enter the character to search for: ";
cin >> findThis;

cout << "The search character was found " << timesFound(textLine, findThis) << " times.\n";

cout << "Would you like to continue? (y/n) ";
cin >> response;

while (response != 'n' && response != 'y')
{
cout << "Would you like to continue? (y/n) ";
cin >> response;
}

if (response == 'n')
running = false;
else
cin.ignore();

}

}

As always I know what the program is supposed to do, but I am lost on how to start. Any help is appreciated. Thank you
 
264
0
Try putting your string into an array of chars and test each index. Let us see your attempt.
 
Well, this isn't the homework forum, so I'm going to take whoever at his word and assume he just wants to know for his own curiosity. Maybe he's learning to program on his own... well, either way, I am going to treat him like an adult and just answer the guy's question.

Alright, so the "string" class in C++ contains an overloaded operator for array-access, the brackets. []

You can use this to check the value of individual characters in the string; so loop over the string's length, checking each character, and if it's equal to the target, increment the counter by one. For instance,

int timesFound(string searchIn, char searchFor)
{
int result = 0;

for(int i = 0; i < searchIn.length(); i++)
{
if(string == searchFor) result++;
}

return result;
}
 

The Physics Forums Way

We Value Quality
• Topics based on mainstream science
• Proper English grammar and spelling
We Value Civility
• Positive and compassionate attitudes
• Patience while debating
We Value Productivity
• Disciplined to remain on-topic
• Recognition of own weaknesses
• Solo and co-op problem solving
Top