"Victor Bazarov" <v.********@comAcast.net> wrote in message news:0KqWc.189
What is the best way to find out how many times a pattern is matched in
a string? For example if I have:
std::string s = "AAAAABBAAAABBAAAABAAABB";
I want to know how many "BB" patterns there are... is there a function
that exists to do this already or do I need to roll my own?
You could write a [simple enough] predicate for 'count_if', given that
"BBB" has two 'BB' patterns, or you need to roll your own if "BBB" should
only have one.
How to do this? The predicate of count_if can only check one char at a
time. I suppose one could do
class IsBB {
public:
explicit IsBB(const char * expect);
bool operator()(const char& arg) const {
const char * a = &lhs;
return strncmp(a, d_expect, strlen(d_expect));
}
private:
const char * d_expect;
};
But it's ugly because in operator()(const char&) we assume that the original
container is a continuous array of chars, which is only true for C style
strings and std::vector<char>, but not std::string and other more exotic
containers.
One could use std::search though.
unsigned int count(const string& s, const string& expect) {
unsigned int count = 0;
typedef string::const_iterator Iter;
Iter iter = s.begin();
const Iter end = s.end();
while (iter!=end) {
Iter find = std::search(iter, end, expect.begin(), expect.end());
if (find == end) break;
++count;
/* either one of the below */
++iter;
iter += expect-end() - expect.begin();
}
return count;
}