views:

375

answers:

1

Hi, 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.

A: 
#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;
}
anon
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().)
yves Baumes
It would depend what I wanted to use the function for. From the questioner's own code, he seems to want non-overlapping occurences.
anon
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 nothing we can do
anon
Thanks, love your names - definitely going to use them in my code.
There is nothing we can do