This sample code searches for every instance of the string "cat" in a given string and counts the total number of instances:
string input;
int i = 0;
int cat_appearances = 0;
getline(cin, input, '\n');
i = input.find("cat", 0);
for(; i != string::npos; i = input.find("cat", i))
{
cat_appearances++;
i++; // Move past the last discovered instance to avoid finding same
// string
}
cout<<cat_appearances;
If it succeeds, it returns the position where the matching subsequence begins. Otherwise, the function returns npos.
(basic_string::npos
static const size_type npos = -1;)
如果成功找到返回位置,否则返回-1.