C 语言 strstr 函数:功能、用法和支持库
strstr 函数是 C 语言标准库函数,支持库是 C 标准库 (libc)。它用于在一个字符串中查找另一个字符串的第一个出现位置。如果找到子字符串,strstr 函数将返回指向子字符串在字符串中第一次出现的指针;否则,它将返回 NULL。
strstr 函数语法:
char *strstr(const char *haystack, const char *needle);
参数:
haystack: 要搜索的字符串。needle: 要查找的子字符串。
返回值:
- 如果找到子字符串,则返回指向子字符串在字符串中第一次出现的指针。
- 如果未找到子字符串,则返回 NULL。
示例:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "This is a sample string.";
char *ptr = strstr(str, "sample");
if (ptr) {
printf("子字符串 'sample' 在字符串中找到,位置:%s\n", ptr);
} else {
printf("子字符串 'sample' 未找到。\n");
}
return 0;
}
输出:
子字符串 'sample' 在字符串中找到,位置:sample string.
注意:
- strstr 函数区分大小写。
- 如果
needle为空字符串 (""),则 strstr 函数将返回haystack的指针。
原文地址: https://www.cveoy.top/t/topic/mC3t 著作权归作者所有。请勿转载和采集!