- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - strstr() 函数
C 库的 strstr() 函数返回指向另一个字符串中指定子字符串的第一个索引的指针。strstr() 的主要目标是在较大的字符串中搜索子字符串,它有助于找到指定子字符串的第一次出现。
语法
以下是 C 库 strstr() 函数的语法:
char *strstr (const char *str_1, const char *str_2);
参数
此函数接受两个参数:
str_1 - 这是主字符串。
str_2 - 要在主字符串(即 str_1)中搜索的子字符串。
返回值
该函数根据以下条件返回值:
如果在 str_1 中找到 str_2,则该函数返回指向 str_1 中 str_2 的第一个字符的指针;如果在 str_1 中未找到 str_2,则返回空指针。
如果 str_2 为空字符串,则返回 str_1。
示例 1
以下是 C 库程序,它使用 strstr() 函数演示了子字符串在主字符串中的存在。
#include <stdio.h>
#include <string.h>
int main () {
const char str[20] = "TutorialsPoint";
const char substr[10] = "Point";
char *ret;
// strstr(main_string, substring)
ret = strstr(str, substr);
// Display the output
printf("The substring is: %s\n", ret);
return(0);
}
输出
执行代码后,我们得到以下结果:
The substring is: Point
示例 2
在这里,我们演示了如何使用 strstr() 函数在主字符串中搜索子字符串。
#include <stdio.h>
#include <string.h>
int main() {
char str_1[100] = "Welcome to Tutorialspoint";
char *str_2;
str_2 = strstr(str_1, "ials");
printf("\nSubstring is: %s", str_2);
return 0;
}
输出
以上代码产生以下结果:
Substring is: ialspoint
这里,前四个字符表示给定字符串的子字符串。
示例 3
在下面的示例中,设置 if-else 条件以检查子字符串是否存在于主字符串中。
#include <stdio.h>
#include <string.h>
int main(){
char str[] = "It is better to live one day as a King";
char target[] = "live";
char *p = strstr(str, target);
if (p)
printf("'%s' is present in the given string \"%s\" at position %ld", target, str, p-str);
else
printf("%s is not present \"%s\"", target, str);
return 0;
}
输出
执行代码后,我们得到以下结果:
'live' is present in the given string "It is better to live one day as a King" at position 16
广告