c++ string庫函數(shù)中查找子串的方法是什么

c++
小樊
81
2024-09-24 22:17:09
欄目: 編程語言

在C++的<string>庫中,查找子串的方法是使用find()函數(shù)。該函數(shù)返回子串在原字符串中第一次出現(xiàn)的位置索引,如果未找到則返回std::string::npos

以下是find()函數(shù)的基本語法:

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

其中,str是要查找的子串,pos是開始查找的位置索引(默認(rèn)為0),返回值是子串在原字符串中第一次出現(xiàn)的位置索引。

以下是一個(gè)簡(jiǎn)單的示例:

#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;
}

輸出結(jié)果為:

子串的起始位置為: 7

0