在C++中,可以使用std::string::find
方法来查找字符串中是否包含某个子串,并返回子串在字符串中的位置。以下是一个示例代码:
#include#include int main() { std::string str = "Hello, world!"; std::string subStr = "world"; size_t found = str.find(subStr); if (found != std::string::npos) { std::cout << "子串在字符串中的位置是:" << found << std::endl; } else { std::cout << "未找到子串" << std::endl; } return 0; }
在上面的示例中,我们首先定义了一个字符串str
和一个子串subStr
,然后使用find
方法查找子串在字符串中的位置,并将结果存储在found
变量中。最后通过判断found
是否等于std::string::npos
来判断是否找到了子串。