如何用c++ string匹配查找子串位置

c++
945
2024/9/25 12:31:22
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,你可以使用std::string类的成员函数find()来查找子串的位置。下面是一个简单的例子:

#include <iostream>
#include <string>

int main() {
    std::string str("Hello, welcome to the world of C++!");
    std::string sub("C++");

    size_t pos = str.find(sub);

    if (pos != std::string::npos) {
        std::cout << "Found '" << sub << "' at position " << pos << std::endl;
    } else {
        std::cout << "'" << sub << "' not found in the string." << std::endl;
    }

    return 0;
}

在这个例子中,我们在字符串"Hello, welcome to the world of C++!"中查找子串"C++"find()函数返回子串在母串中首次出现的位置(从0开始计数)。如果子串不存在于母串中,find()函数将返回std::string::npos

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

推荐阅读: c++中enum class的用法是什么