Check if a string contains a string in C++

Check if a string contains a string in C++

Use std::string::find as follows:

if (s1.find(s2) != std::string::npos) {
    std::cout << found! << n;
}

Note: found! will be printed if s2 is a substring of s1, both s1 and s2 are of type std::string.

You can try using the find function:

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

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

Check if a string contains a string in C++

Starting from C++23 you can use std::string::contains

#include <string>

const auto haystack = std::string(haystack with needles);
const auto needle = std::string(needle);

if (haystack.contains(needle))
{
    // found!
}

Leave a Reply

Your email address will not be published.