Start learning free

LESSON 61 OF 667 · STRINGS I

String Find in C++

Lesson

In C++, you can find the index of a substring using std::string::find():

s.find(sub)          // returns index of first occurrence, or string::npos if not found
s.rfind(sub)         // returns index of last occurrence
s.find(sub, start)   // search starting from index `start`

Here are some examples:

string sentence = "Hello World";
int idx = sentence.find("World");
cout << idx;  // 6

if (sentence.find("xyz") == string::npos) {
    cout << "not found";
}

The index returned is the position of the first character of the found substring. Returns string::npos (a large number) if not found.


Assignment
Follow the Coding Tutorial and find the index of "World" in sentence!


Hint
Use sentence.find("World") and assign the result to idx.

STEP 1 OF 1
    Ctrl + Enter to check