I would like to know how to count how many times a string is repeated within another string in C++.
I have only found ways to count repetition but only for one character.
What I would like would be that, for example, if I have a string p="AJAJDJSDJSDJNBDSJJAJSDKANSDKKSJAJSJSJSDAANSJDANSNADNAS", what I would like to do is know how many "AJA" there are, how many "JSKA" there are, how many "DANSN" there are... in that string p.
The only similar thing I have found and have done is the following:
#include <iostream>
#include<string>
#include<string.h>
#include<stdlib.h>
using namespace std;
int main(){
string string1="NLNNCCCL";
string string2="CCCL";
if (string1.find(string2) != std::string::npos) {
std::cout << "se encontró!"<<endl;
}
system("pause");
return 0;
}
But in that code I only ensure the existence of the typed pattern (string2) but not the times it is repeated in string1
The following code snippet represents another way to look up the number of occurrences of the given substring within a source string. I've placed the count function separately in case you want to use it within your code.
You just have to add a loop, so that the search is repeated as long as matches are found:
Since it
std::string.find( )
supports a 2nd argument to indicate at which position to start the search, we take advantage of it to start each search just after the position where the last occurrence was found; hence the++idx
.Is it a trick question? Keep in mind that the repetition of one chain within another can have nuances, for example, how many repetitions of
"123123"
should be counted in"123123123"
? One or two?If the answer is the latter, you can use a function like this:
If the answer is the first, the function should start searching at the end of the found string, not at the beginning: