c++

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

小樊
172
2024-08-08 23:07:37
栏目: 编程语言
C++开发者专用服务器,限时0元免费领! 查看>>

在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。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

相关推荐:C++ str.find的用法及示例代码

0
看了该问题的人还看了