溫馨提示×

如何在C++中使用str.find查找子串

c++
小樊
173
2024-08-08 23:08:36
欄目: 編程語言

在C++中,可以使用std::string::find方法來查找字符串中是否包含某個子串,并返回子串在字符串中的位置。以下是一個示例代碼:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello, world!";
    std::string subStr = "world";

    size_t found = str.find(subStr);
    if (found != std::string::npos) {
        std::cout << "子串在字符串中的位置是:" << found << std::endl;
    } else {
        std::cout << "未找到子串" << std::endl;
    }

    return 0;
}

在上面的示例中,我們首先定義了一個字符串str和一個子串subStr,然后使用find方法查找子串在字符串中的位置,并將結果存儲在found變量中。最后通過判斷found是否等于std::string::npos來判斷是否找到了子串。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女