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";
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
string::findtakes 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, orstring::nposif the string is not found.The variable
startstarts at 0 (the first character) and in the condition of the loop, you usestartto tellfindwhere to start looking, then assign the return value offindtostart. Increment the occurrence count; now thatstartholds the position of the string, you can skipto_find_occurrences_of.length()1 characters ahead and start looking again.1 drhirsch makes the point that if
to_find_occurrences_ofcontains a repeated sequence of characters, doingstart += to_find_occurrences_of.length()may skip some occurrences. For instance, ifbase_stringwas"ffff"andto_find_occurrences_ofwas"ff", then only 2 occurrences would be counted if you addto_find_occurrences_of.length()tostart. If you want to avoid that, add 1 instead ofto_find_occurrences_of.length()tostart, and in that example, 3 occurrences would be counted instead of just 2.