C语言函数strstr如何使用

   2025-02-20 2770
核心提示:函数strstr用于在一个字符串中搜索另一个字符串的出现位置。它的声明如下:char *strstr(const char *haystack, const char *nee

函数strstr用于在一个字符串中搜索另一个字符串的出现位置。它的声明如下:

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

其中,haystack表示要搜索的字符串,needle表示要搜索的子字符串。

使用方法如下:

#include <stdio.h>#include <string.h>int main(){const char *haystack = "Hello, World!";const char *needle = "World";char *result = strstr(haystack, needle);if(result != NULL){printf("'%s' is found in '%s' at position %ld\n", needle, haystack, result - haystack);}else{printf("'%s' is not found in '%s'\n", needle, haystack);}return 0;}

输出结果为:

'World' is found in 'Hello, World!' at position 7

上述代码中,首先定义了一个haystack字符串和一个needle字符串。然后使用strstr函数在haystack字符串中搜索needle字符串的出现位置。如果找到了,则返回指向该位置的指针;如果未找到,则返回NULL。最后根据返回的结果进行相应的输出。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言