C++ str.find的参数及使用技巧

   2024-10-02 3490
核心提示:在C++中,str.find()函数用于在字符串中查找特定子串的位置。其参数包括要查找的子串以及可选的起始位置。语法如下:size_t find

在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 << "子串在字符串中的位置为:" << found << std::endl;    } else {        std::cout << "子串未找到" << std::endl;    }        return 0;}

在上面的示例中,我们使用find()方法在字符串中查找子串"World"的位置,并输出结果。如果子串存在,则返回子串在字符串中的起始位置,否则返回std::string::npos。

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

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