溫馨提示×

c++ contains函數怎樣使用

c++
小樊
342
2024-07-16 00:05:49
欄目: 編程語言

在C++中,std::string類和C-style字符串都提供了std::string::find()方法來檢查是否包含指定的子字符串。下面是一個使用std::string::find()方法的簡單示例:

#include <iostream>
#include <string>

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

    if (str.find(subStr) != std::string::npos) {
        std::cout << "The string contains the substring." << std::endl;
    } else {
        std::cout << "The string does not contain the substring." << std::endl;
    }

    return 0;
}

在上面的示例中,我們首先定義了一個std::string類型的字符串str和一個要查找的子字符串subStr。然后,我們使用str.find(subStr)方法查找subStrstr中的位置。如果返回值不等于std::string::npos,則表示字符串包含子字符串。

另外,對于C-style字符串,可以使用strstr()函數來檢查是否包含指定的子字符串。下面是一個使用strstr()函數的簡單示例:

#include <iostream>
#include <cstring>

int main() {
    const char* str = "Hello, world!";
    const char* subStr = "world";

    if (strstr(str, subStr) != nullptr) {
        std::cout << "The string contains the substring." << std::endl;
    } else {
        std::cout << "The string does not contain the substring." << std::endl;
    }

    return 0;
}

在上面的示例中,我們首先定義了一個C-style字符串str和一個要查找的子字符串subStr。然后,我們使用strstr()函數查找subStrstr中的位置。如果返回值不為nullptr,則表示字符串包含子字符串。

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