C++ strstr函数的正确用法

   2024-10-11 9650
核心提示:strstr函数是用于在字符串中查找指定子字符串的函数。它的原型为:char *strstr(const char *haystack, const char *needle);其

strstr函数是用于在字符串中查找指定子字符串的函数。它的原型为:

char *strstr(const char *haystack, const char *needle);

其中,haystack是要在其中搜索的字符串,needle是要搜索的子字符串。

使用strstr函数的正确用法如下:

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

上面的代码首先定义了两个字符串haystack和needle,然后调用strstr函数在haystack中查找needle字符串。如果找到了,则打印出其位置;否则打印出"Not found"。

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

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