Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting the number of occurrences of a string within a string

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

Example: counting the occurrences of Foo inside FooBarFooBarFoo

like image 612
MBZ Avatar asked Mar 18 '14 19:03

MBZ


People also ask

How do you count the number of occurrences of a string in a string?

The count() method returns the number of occurrences of a substring in the given string.

How do you count how many times a value appears in a string?

The count() method returns the number of times a specified value appears in the string.

How do you count specific occurrences of characters in a string?

Given a string and a character, the task is to make a function which count occurrence of the given character in the string. Examples: Input : str = "geeksforgeeks" c = 'e' Output : 4 'e' appears four times in str. Input : str = "abccdefgaa" c = 'a' Output : 3 'a' appears three times in str.


1 Answers

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;

}
like image 184
taocp Avatar answered Oct 05 '22 11:10

taocp