温馨提示×

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

c++
小樊
110
2024-08-08 23:07:37
栏目: 编程语言

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

0