溫馨提示×

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

c++
小樊
81
2024-09-25 08:50:11
欄目: 編程語言

在C++中,你可以使用std::string類的成員函數(shù)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()函數(shù)返回子串在母串中首次出現(xiàn)的位置(從0開始計數(shù))。如果子串不存在于母串中,find()函數(shù)將返回std::string::npos。

0