c++中strstr函数的用法是什么

   2024-11-04 3190
核心提示:在C++中,strstr函数用于在一个字符串中搜索指定子字符串的位置。其原型如下:char* strstr(const char* str1, const char* str2

在C++中,strstr函数用于在一个字符串中搜索指定子字符串的位置。其原型如下:

char* strstr(const char* str1, const char* str2);

其中,str1是要搜索的字符串,str2是要查找的子字符串。strstr函数会返回指向第一次出现str2的位置的指针,如果找不到则返回nullptr

示例代码:

#include <iostream>#include <cstring>int main() {    const char* str1 = "Hello, world!";    const char* str2 = "world";    char* result = strstr(str1, str2);    if (result) {        std::cout << "Found at position: " << result - str1 << std::endl;    } else {        std::cout << "Not found" << std::endl;    }    return 0;}

输出结果为:

Found at position: 7

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

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