You can search strings to find the first or last instance of a substring.
If the string contains the required substring, the position of the substring found by the search is returned.
If not, a pseudo-position npos, or -1, is returned.
The npos constant is defined in the string class, you can reference it as string::npos.
The find() method returns the position at which a substring was first found in the string.
The method requires the substring to be located as an argument.
string s1("this is a test"); int first = s1.find("test");
You can use the "right find" method rfind() to locate the last occurrence of a substring in a string.
int last = s1.rfind("is");
#include <iostream> #include <string> using namespace std; int main() // w w w.ja v a2s. c o m { string s1("this is a test"); int first = s1.find("test"); cout << first << endl; int last = s1.rfind("is"); cout << last << endl; return 0; }