How to find occurrences of a string in string in C++?
Here is the Scenario.
string base_string = "BF;1;2;3;FF;10;20;30;BF;11;;22;33;FF;100;200;300;BF;110;;220;330;FF;1000;2000;3000";
string to_find_occurances_of = "BF";
The strdup() and strndup() functions are used to duplicate a string. strdup() : Syntax : char *strdup(const char *s);
int occurrences = 0;
string::size_type start = 0;
while ((start = base_string.find(to_find_occurrences_of, start)) != string::npos) {
++occurrences;
start += to_find_occurrences_of.length(); // see the note
}
string::find
takes a string to look for in the invoking object and (in this overload) a character position at which to start looking, and returns the position of the occurrence of the string, or string::npos
if the string is not found.
The variable start
starts at 0 (the first character) and in the condition of the loop, you use start
to tell find
where to start looking, then assign the return value of find
to start
. Increment the occurrence count; now that start
holds the position of the string, you can skip to_find_occurrences_of.length()
1 characters ahead and start looking again.
to_find_occurrences_of
contains a repeated sequence of characters, doing start += to_find_occurrences_of.length()
may skip some occurrences. For instance, if base_string
was "ffff"
and to_find_occurrences_of
was "ff"
, then only 2 occurrences would be counted if you add to_find_occurrences_of.length()
to start
. If you want to avoid that, add 1 instead of to_find_occurrences_of.length()
to start
, and in that example, 3 occurrences would be counted instead of just 2.
Here the code to find string occurance in string with user defined Find function
int Find(char OrgStr[], char szFind[]);
void main(){
int iCount = Find("babbabaab ab", "ab");
//cout<<"No of 'abe' : " << iCount <<endl;
}
int Find(char orgStr[], char findStr[]){
int i,j,k,l,szLen,orgLen;
char temp[] = " ";
orgLen = strlen(orgStr);
szLen = strlen(findStr);
k= 0;
i = 0;
l = 0;
while( l < orgLen )
{
i = (orgLen - ( orgLen - l));
for( j = 0; j < szLen; j++)
{
temp[j] = orgStr[i];
i++;
}
temp[j] = '\0';
if(strcmp(temp,findStr) == 0)
{
k++;
}
strcpy(temp,"");
l++;
}
cout<<"No of 'ab' : " << k <<endl;
return k;
//strcpy(temp,"");
}
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