c语言

C语言函数strstr如何使用

小亿
106
2023-09-29 00:38:39
栏目: 编程语言

函数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。最后根据返回的结果进行相应的输出。

0
看了该问题的人还看了