What's the best way of counting all the occurrences of a substring inside a string?
Example: counting the occurrences of Foo
inside FooBarFooBarFoo
The count() method returns the number of occurrences of a substring in the given string.
The count() method returns the number of times a specified value appears in the 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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With