This tutorial will discuss about a unique way to check if a string contains a substring in C++.
To check if a string contains another string or not, we can use the find()
function of string
class in C++. It returns the index position of first occurrence of the given substring in the string. If the given substring does not exists in the string, then it will return std::string::npos
.
We have created a function to check if a string contains a substring or not using the string::find()
function,
// Returns True if string contains // the given sub string. bool contains( const std::string& str, const std::string& subString) { // Check if substring exists in string return str.find(subString) != std::string::npos; }
This function accepts two strings as arguments, and returns True
if the first string
contains the second string
. Internally, it uses the std::string::find()
function to locate the substring in main string.
Let’s see the complete example,
Pointers in C/C++ [Full Course]
#include <iostream> #include <string> // Returns True if string contains // the given sub string. bool contains( const std::string& str, const std::string& subString) { // Check if substring exists in string return str.find(subString) != std::string::npos; } int main() { std::string str = "This is a sample text"; std::string subString = "sample"; // Check if string contains a substring if (contains(str, subString)) { std::cout << "Yes, String contains the substring \n"; } else { std::cout << "No, String does not contains the substring \n"; } return 0; }
Output :
Yes, String contains the substring
Summary
Today we learned about several ways to check if a string contains a substring in C++. Thanks.