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.
source
share