在C++中,std::string类和C-style字符串都提供了std::string::find()方法来检查是否包含指定的子字符串。下面是一个使用std::string::find()方法的简单示例:
#include <iostream> #include <string> int main() { std::string str = "Hello, world!"; std::string subStr = "world"; if (str.find(subStr) != std::string::npos) { std::cout << "The string contains the substring." << std::endl; } else { std::cout << "The string does not contain the substring." << std::endl; } return 0; } 在上面的示例中,我们首先定义了一个std::string类型的字符串str和一个要查找的子字符串subStr。然后,我们使用str.find(subStr)方法查找subStr在str中的位置。如果返回值不等于std::string::npos,则表示字符串包含子字符串。
另外,对于C-style字符串,可以使用strstr()函数来检查是否包含指定的子字符串。下面是一个使用strstr()函数的简单示例:
#include <iostream> #include <cstring> int main() { const char* str = "Hello, world!"; const char* subStr = "world"; if (strstr(str, subStr) != nullptr) { std::cout << "The string contains the substring." << std::endl; } else { std::cout << "The string does not contain the substring." << std::endl; } return 0; } 在上面的示例中,我们首先定义了一个C-style字符串str和一个要查找的子字符串subStr。然后,我们使用strstr()函数查找subStr在str中的位置。如果返回值不为nullptr,则表示字符串包含子字符串。