温馨提示×

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

c++
小樊
100
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