String.h如何查找子字符串

   2024-10-07 2600
核心提示:在C++中,可以使用std::string类的find()方法来查找子字符串。具体示例如下:#include iostream#include stringint main() {std:

在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。最后根据返回值输出相应的结果。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号