check if a string is a substring of another string in c++ code example

Example 1: how to check string contains char in c++

std::string s = "Hello";
if (s.find('e') != std::string::npos)
    cout << "Found";
else
    cout << "Not Found";

Example 2: c++ check if string contains substring

string str ("There are two needles in this haystack.");
string str2 ("needle");

if (str.find(str2) != string::npos) {
//.. found.
}

Example 3: c++ string contains

if (string1.find(string2) != std::string::npos) {
    std::cout << "found!" << '\n';
}

Tags:

Cpp Example