CodeBlanks Logo Icon CodeBlanks

String search

Learn to search in a string with .find().

The find method

To search for one string inside another you use the find method. The call s.find("needle") returns the index of the first occurrence of the needle. If it is not found, the method returns std::string::npos.

For example std::string s = "paris lyon marseille"; s.find("lyon") returns 6 because "lyon" starts at index 6. Indices count from zero and spaces count as characters too.

Checking with npos

When find cannot locate the searched string it returns std::string::npos, a special constant meaning "not found". To check whether a string contains another you use this pattern:

if (s.find("x") == std::string::npos) { /* not found */ }. This pattern is useful for banned word checks in user input or for looking up an extension in a file name.

Practice Find a city

The sentence variable is set to "paris lyon marseille" and word is set to "lyon". Assign the result of sentence.find(word) to pos and print it with std::cout. The output must be 6.

Starter code

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string sentence = "paris lyon marseille";
    std::string word = "lyon";
    // Find word inside sentence, assign to pos and print
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string sentence = "paris lyon marseille";
    std::string word = "lyon";
    int pos = sentence.find(word);
    std::cout << pos << std::endl;
    return 0;
}

Expected output

6

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Write the find call

Question
std::string s = "Welcome";
int pos = s____("co");
Answer
std::string s = "Welcome";
int pos = s.find("co");

Explanation: .find("co") returns the index of "co".

2 Match each find call to its result

Term Meaning
s.find("Wel") on "Welcome" 0
s.find("co") on "Welcome" 3
s.find("xy") on "Welcome" std::string::npos
s.find("om") on "Welcome" 4

3 What does find return when the needle is not in the string?

main.cpp
std::string s = "Welcome";
s.find("xy")
  • -1
  • 0
  • std::string::npos Correct answer
  • ""

Explanation: When not found, std::string::npos is returned.

All lessons in Beginner