c++

c++ string库函数中查找子串的方法是什么

小樊
81
2024-09-24 22:17:09
栏目: 编程语言

在C++的<string>库中,查找子串的方法是使用find()函数。该函数返回子串在原字符串中第一次出现的位置索引,如果未找到则返回std::string::npos

以下是find()函数的基本语法:

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

其中,str是要查找的子串,pos是开始查找的位置索引(默认为0),返回值是子串在原字符串中第一次出现的位置索引。

以下是一个简单的示例:

#include <iostream>
#include <string>

int main() {
    std::string str("Hello, world!");
    std::string sub("world");

    std::size_t pos = str.find(sub);

    if (pos != std::string::npos) {
        std::cout << "子串的起始位置为: " << pos << std::endl;
    } else {
        std::cout << "未找到子串" << std::endl;
    }

    return 0;
}

输出结果为:

子串的起始位置为: 7

0
看了该问题的人还看了