The following code will find the count of the non-overlapping occurrences of a given string.
using namespace std;
static int countOccurences(const string & line, const string & symbol) {
if (symbol.empty()) return 0;
if (line.empty()) return 0;
int resultCount = 0;
for (size_t offset = line.find(symbol); offset != string::npos;
offset = line.find(symbol, offset + symbol.length()))
{
resultCount++;
}
return resultCount;
}
int main(int argc, const char * argv[])
{
cout << countOccurences("aaabbb","b") << endl;
return 0;
}
The find function will return either an iterator to the first element of the value it matches to or return 'last' hence string::npos. This ensures no overlap with offset + symbol.length().
I did my best to translate the variables to English for readability for English users.