This post will discuss how to check if a string contains another string in C++.

1. Using string::find

A simple solution is to use the string::find algorithm to search the specified substring in the string. It returns the index of the first instance of the specified substring or string::npos if the substring is not present.

Download  Run Code

Output:

String found

2. Using Boost

If the boost library is available, try using the boost::algorithm::contains algorithm in the header <boost/algorithm/string.hpp>. This function can be invoked as:

Download Code

Output:

String found

3. Using strstr() function

Finally, you can convert both strings to C-strings using the c_str() function and compare them using the strstr() function. It returns a pointer to the first occurrence of the substring in the given string, or a null pointer if the substring is not found.

Download  Run Code

Output:

String found

4. Using basic_string::contains

With C++23, you can use the much-awaited basic_string::contains function to check whether a string contains the given substring. It returns true if the string contains the specified substring, and false otherwise.

Download  Run Code

Output:

String found

That’s all about checking if a string contains another string in C++.