// pgm33 // using the C++ string class: find // 11/23/2016 #include #include #include #include #include using namespace std; int main() // string::find { string str ("There are two needles in this haystack with needles."); string str2 ("needle"); // different member versions of find in the same order as above: size_t found = str.find(str2); if (found != string::npos) cout << "first 'needle' found at location: " << found << '\n'; found=str.find("needle",found+1); // if found if (found!=string::npos) cout << "second 'needle' found at location: " << found << '\n'; found=str.find("haystack", 0); if (found!=string::npos) cout << "'haystack' also found at: " << found << '\n'; found=str.find('.', 0); if (found!=string::npos) std::cout << "Period found at: " << found << '\n'; string text="finding all substrings in a longer string"; string pattern="in"; // count how many times the pattern occurs in the text size_t pos=text.find(pattern); int numocc=0; while(pos!=string::npos) { numocc++; pos=text.find(pattern,pos+1); } cout << "The number of occurrences of " << pattern << " in the text " << endl << text << endl << " is " << numocc << endl; return 0; }