The find() Family

Here are the find() prototypes as provided by C++11:

size_type find (const basic_string& str, size_type pos = 0) const noexcept;
size_type find (const charT* s, size_type pos = 0) const;
size_type find (const charT* s, size_type pos, size_type n) const;
size_type find (charT c, size_type pos = 0) const noexcept;

The first member returns the beginning position of the str substring’s first occurrence in the invoking object, with the search beginning at position pos. If the substring is not found, the method returns npos.

Here’s code for finding the location of the substring "hat" in a longer string:

string longer("That is a funny hat.");
string shorter("hat");
size_type loc1 = longer.find(shorter);           // sets loc1 to 1
size_type loc2 = longer.find(shorter, loc1 + 1); // sets loc2 to 16

Because the second search begins at position 2 (the a in That), the first occurrence of hat it finds is near the end of the string. To test for failure, you use the string::npos value:

if (loc1 == string::npos)
    cout << "Not found ";

The second method does the same thing, except that it uses an array of characters instead of a string object as the substring:

size_type loc3 = longer.find("is");              //sets loc3 to 5

The third method does the same as the second, except that it uses only the first n characters of the string s. The effect is the same as using the basic_string(const charT* s, size_type n) constructor and using the resulting object as the string argument to the first form of find(). For example, the following searches for the substring "fun":

size_type loc4 = longer.find("funds", 3);        //sets loc4 to 10

The fourth method does the same thing as the first, except that it uses a single character instead of a string object as the substring:

size_type loc5 = longer.find('a'),               //sets loc5 to 2

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.39.60