Counting the number of occurrences of a string within a string

MBZ picture MBZ · Mar 18, 2014 · Viewed 20.5k times · Source

What's the best way of counting all the occurrences of a substring inside a string?

Example: counting the occurrences of Foo inside FooBarFooBarFoo

Answer

taocp picture taocp · Mar 18, 2014

One way to do is to use std::string find function:

#include <string>
#include <iostream>
int main()
{
   int occurrences = 0;
   std::string::size_type pos = 0;
   std::string s = "FooBarFooBarFoo";
   std::string target = "Foo";
   while ((pos = s.find(target, pos )) != std::string::npos) {
          ++ occurrences;
          pos += target.length();
   }
   std::cout << occurrences << std::endl;

}