溫馨提示×

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

c++
小樊
152
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女