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:

  1. Using the find() function:
  2. The find() function is a member function of the std::string class in C++.
  3. It returns the position of the first occurrence of the substring within the string, or std::string::npos if the substring is not found.
  4. Here is the syntax: string.find(substring);
  5. The find() function takes the substring as an argument and returns the position of its first occurrence. If the substring is not found, it returns std::string::npos.
  6. To check if the string contains the substring, you can compare the result of find() with std::string::npos.

  7. Using the strstr() function:

  8. The strstr() function is a standard C library function that can be used to find the first occurrence of a substring within a string.
  9. Here is the syntax: strstr(string.c_str(), substring.c_str());
  10. The strstr() function takes two arguments: the C-style string (converted from the C++ string using .c_str()) and the C-style substring.
  11. It returns a pointer to the first occurrence of the substring within the string, or nullptr if the substring is not found.
  12. To check if the string contains the substring, you can check if the result of strstr() is not equal to nullptr.

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.