3

is there any STL algorithm or a standard way of finding how many occurences of particular substring are there in a string? For example in string:

'How do you do at ou'

the string "ou" appears twice. I tried some STL algorithms with and without predicates but what I found is that those algorithms from STL want to compare components of string which in my case is char but cannot? compare substrings. I come up with something like this:

str - string

obj - substring we're looking for

std::string::size_type count_subs(const std::string& str, const std::string& obj)
{
std::string::const_iterator beg = str.begin();
std::string::const_iterator end = str.end();
std::string::size_type count = 0;
while ((beg + (obj.size() - 1)) != end)
{
    std::string tmp(beg, beg + obj.size());
    if (tmp == obj)
    {
        ++count;
    }
    ++beg;
}
return count;
}

thank you.

1 Answer 1

5
#include <string>
#include <iostream>

int Count( const std::string & str, 
           const std::string & obj ) {
    int n = 0;
    std::string ::size_type pos = 0;
    while( (pos = obj.find( str, pos )) 
                 != std::string::npos ) {
        n++;
        pos += str.size();
    }
    return n;
}

int main() {
    std::string s = "How do you do at ou";
    int n = Count( "ou", s );
    std::cout << n << std::endl;
}
Sign up to request clarification or add additional context in comments.

5 Comments

Question: In the string "oooo" Would you count the pattern "oo" twice or three times. (Personnaly I would count it three time, and therefore fo ++pos instead of pos += str.size().)
It would depend what I wanted to use the function for. From the questioner's own code, he seems to want non-overlapping occurences.
Thank you for your answer - although I think that there is logical error - it should be str.find(obj,pos). Anyway, so basically there is no way in which one can use STL alg. like count_if or one similar to it to avoid explicit loop. Pity. I wonder if guys from boost have any recipe for that problem.
There is no error - my version searches for str in obj - I slightly misread your code & so got them the other way round from you. This indicates the neeed for better names, such as 'needle' and 'haystack'. As for avoiding the explicit loop - anything that used an algorithm and a predicate would actually be more code. Sometimes the simplest old skool solution may be the best.
Thanks, love your names - definitely going to use them in my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.