Finding a substring from multiple occurrences in a string [C ++]

Is there any STL algorithm or standard way to determine the number of occurrences of a particular substring in a string? For example, in the line:

'How do you do at ou'

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

str - string

obj is the substring we are 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;
}

thanks.

+3
source share
1 answer
#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;
}
+5
source

Source: https://habr.com/ru/post/1724606/


All Articles