c++ string匹配如何實(shí)現(xiàn)精確查找

c++
小樊
81
2024-09-25 08:45:15

在C++中,要實(shí)現(xiàn)精確的字符串匹配,可以使用std::string類的成員函數(shù)find()find()函數(shù)可以在一個(gè)字符串中查找指定的子串,如果找到了子串,它會(huì)返回子串在原字符串中的起始位置;如果沒(méi)有找到子串,它會(huì)返回std::string::npos。

下面是一個(gè)簡(jiǎn)單的例子,展示了如何使用find()函數(shù)實(shí)現(xiàn)精確查找:

#include <iostream>
#include <string>

int main() {
    std::string str("Hello, I am a C++ assistant.");
    std::string pattern("C++");

    size_t pos = str.find(pattern);

    if (pos != std::string::npos) {
        std::cout << "Pattern found at position: " << pos << std::endl;
    } else {
        std::cout << "Pattern not found." << std::endl;
    }

    return 0;
}

在這個(gè)例子中,我們?cè)谧址?code>"Hello, I am a C++ assistant."中查找子串"C++"。find()函數(shù)返回子串在原字符串中的起始位置,即7。

0