Write a recursive function that returns number of occurrences of a certain letter in a given string.
Let the function prototype be int countLetter(char letter, string str). For example, if
letter = "l" and str = "lollipop", the function should return 3.
#include <iostream>
#include <string>
using namespace std;
int countLetter(char letter, string str) {
if (str.size() == 0) {
return 0;
}
return countLetter(letter, str.substr(1))
+ (str[0] == letter ? 1 : 0);
}
int main() {
string str;
char letter;
cin >> str;
cin >> letter;
cout << countLetter(letter, str);
return 0;
}
Comments
Leave a comment