strstr
用途
strstr
是 C 语言标准库中的一个函数,用于在字符串中查找子串。
原型
char *strstr(const char *haystack, const char *needle);
说明
strstr
函数在字符串 haystack
中查找子串 needle
,如果找到,则返回指向子串的指针;否则,返回 NULL
。
strstr
函数的参数 haystack
和 needle
都是指向字符串的指针。haystack
表示要搜索的字符串,needle
表示要查找的子串。
strstr
函数的返回值是一个指向子串的指针,指向 haystack
中 needle
的第一个字符。如果 needle
不在 haystack
中,则返回 NULL
。
示例
下面是一个简单的示例:
#include <stdio.h>
#include <string.h>
int main() {
char haystack[] = "Hello, World!";
char needle[] = "World";
char *result = strstr(haystack, needle);
if (result != NULL) {
printf("找到子串: %s\n", result);
} else {
printf("未找到子串\n");
}
return 0;
}
在这个示例中,我们查找字符串 "Hello, World!" 中是否包含子串 "World"。由于找到了子串,strstr
函数返回指向 "World" 的指针,程序输出 "找到子串: World"。
本文来自博客园,作者:flxx,转载请注明原文链接:https://www.cnblogs.com/faithlocus/p/18020419