Answer to Question #315127 in C++ for Bassem Remon

Question #315127

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.

1
Expert's answer
2022-03-21T12:36:07-0400
#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;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog