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

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

在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来判断是否找到了子串。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号