In this C++ tutorial, you will learn how to check if a given string contains a specific substring value, with example programs.

Check if the string contains a specific substring in C++

To check if the given string contains a specific substring in C++, you can use find() method of string class.

1. Checking if string contains substring using find() method in C++

In the following program, we are given a string in str and the substring in substring. We have to check if the string str contains substring using find() method.

Steps

  1. Given an input string in str, and a specific substring in substring.
  2. Call the find() method of the string class to search for the substring within the str.
  3. If the find() method returns a value other than string::npos, it means the substring was found, indicating that str contains the substring. Use this information to create a condition that returns true only if the string str contains the substring.
  4. Write a C++ if else statement with the condition created from the previous step.

Program

main.cpp

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";
    string substring = "llo";

    if (str.find(substring) != string::npos) {
        cout << "The string contains the substring." << endl;
    } else {
        cout << "The string does not contain the substring." << endl;
    }

    return 0;
}

Output

The string contains the substring.

Now, let us change the substring value such that the string str does not contain substring, and run the program again.

main.cpp

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str = "Hello World";
    string substring = "apple";

    if (str.find(substring) != string::npos) {
        cout << "The string contains the substring." << endl;
    } else {
        cout << "The string does not contain the substring." << endl;
    }

    return 0;
}

Output

The string does not contain the substring.
ADVERTISEMENT

Conclusion

In this C++ Tutorial, we learned how to check if the string contains the specified substring value using string find() method, with examples.