c++ check if string contains substring
To check if a C++ string contains a substring, you can use the find()
function or the strstr()
function. Here is how you can do it:
- Using the
find()
function: - The
find()
function is a member function of thestd::string
class in C++. - It returns the position of the first occurrence of the substring within the string, or
std::string::npos
if the substring is not found. - Here is the syntax:
string.find(substring);
- The
find()
function takes the substring as an argument and returns the position of its first occurrence. If the substring is not found, it returnsstd::string::npos
. To check if the string contains the substring, you can compare the result of
find()
withstd::string::npos
.Using the
strstr()
function:- The
strstr()
function is a standard C library function that can be used to find the first occurrence of a substring within a string. - Here is the syntax:
strstr(string.c_str(), substring.c_str());
- The
strstr()
function takes two arguments: the C-style string (converted from the C++ string using.c_str()
) and the C-style substring. - It returns a pointer to the first occurrence of the substring within the string, or
nullptr
if the substring is not found. - To check if the string contains the substring, you can check if the result of
strstr()
is not equal tonullptr
.
Here are code examples for both approaches:
#include <iostream>
#include <string>
int main() {
std::string str = "Hello, world!";
std::string substring = "world";
// Using the find() function
if (str.find(substring) != std::string::npos) {
std::cout << "Substring found using find()" << std::endl;
} else {
std::cout << "Substring not found using find()" << std::endl;
}
// Using the strstr() function
if (strstr(str.c_str(), substring.c_str()) != nullptr) {
std::cout << "Substring found using strstr()" << std::endl;
} else {
std::cout << "Substring not found using strstr()" << std::endl;
}
return 0;
}
In this example, the string str
contains the substring "world". The find()
function and the strstr()
function are used to check if the string contains the substring. The appropriate message is printed based on the result of the check.