C++ str.find方法用法解析

   2024-10-02 7400
核心提示:在C++中,str.find()方法用于在字符串中查找特定的子字符串,并返回子字符串在原字符串中第一次出现的位置。该方法的语法如下:s

在C++中,str.find()方法用于在字符串中查找特定的子字符串,并返回子字符串在原字符串中第一次出现的位置。该方法的语法如下:

size_t find (const string& str, size_t pos = 0) const noexcept;

其中,str表示要查找的子字符串,pos表示开始查找的位置,默认为0。

使用示例:

#include <iostream>#include <string>int main() {    std::string str = "Hello, world!";    std::string sub = "world";    size_t found = str.find(sub);    if (found != std::string::npos) {        std::cout << "Subtring found at position: " << found << std::endl;    } else {        std::cout << "Substring not found" << std::endl;    }    return 0;}

在上面的示例中,我们首先定义了一个字符串str和一个子字符串sub,然后使用str.find(sub)方法来查找子字符串在原字符串中的位置。如果找到了子字符串,则返回其在原字符串中的位置,如果没有找到则返回std::string::npos。

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

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