compute recursively the number of times
that sub appears in the string, without the
sub strings overlapping.

str_count("catcowcat", "cat") returns 2
str_count("catcowcat", "cow") returns 1
str_count("catcowcat", "dog") returns 0

please give me some idea to solve this problem

int str_count(string str, string sub)
{
    int len = str.length();
    int s_len = sub.length();
    
    if(len < s_len) return 0;
    else if(len >= s_len)
    {
        if(str.substr(0,s_len) == sub) return 1 + str_count(str.substr(s_len), sub);
        else return 0 + str_count(str.substr(s_len), sub);
    }
}

my code doesn't work for
str_count("cacatcowcat", "cat")
it return 0 for this case.

problem:
you will always get zero because of line #6; you are exiting your function based soley on string sizes...


answer:
one little tip on recursion that i found out on my own... Generally, for recursive functions, the return value of your function should also be a function parameter. any function that deviates from this will lose it's recursive properties.

currently, your function does not meet this little rule, because it returns an int, but only has string type args.

your function returns an int (the number of substrings found in a string). we should also pass this value into the function as an argument. we can use this value to 'keep track' of how many substrings we've attempted to identify. Now we can establish a clear exit case; In Pseudocode: if(number of attempts >= number of substrings) then return number of substrings found.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.