如何在C++中使用str.find查找子串

avatar
作者
筋斗云
阅读量:0

在C++中,可以使用std::string::find方法来查找字符串中是否包含某个子串,并返回子串在字符串中的位置。以下是一个示例代码:

#include <iostream> #include <string>  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来判断是否找到了子串。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!