C++ String Contains Substring: Quick Guide

In C++, the find function can be used to determine if one string contains another string. The find function returns the position of the first occurrence of the searched string within the main string, or string::npos if not found.

The example code is shown below:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, World!";
    std::string substr = "Hello";

    if (str.find(substr) != std::string::npos) {
        std::cout << "字符串包含子字符串" << std::endl;
    } else {
        std::cout << "字符串不包含子字符串" << std::endl;
    }

    return 0;
}

In this example, we are checking if the string str contains the substring substr. If it does, we output that the string contains the substring; otherwise, we output that the string does not contain the substring.

bannerAds