温馨提示×

String.h如何查找子字符串

小樊
82
2024-06-29 12:17:40
栏目: 编程语言

在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()方法在字符串str中查找子字符串subStr的位置,并将返回值存储在found变量中。如果find()方法找到了子字符串,则返回子字符串在原字符串中的位置,否则返回std::string::npos。最后根据返回值输出相应的结果。

0