c++

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

小樊
81
2024-09-25 08:50:11
栏目: 编程语言

在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

0
看了该问题的人还看了