C 语言中的 strstr() 函数是什么?
C 库函数char *strstr(const char *haystack, const char *needle) 用于在字符串haystack中查找子字符串needle的第一个出现位置。终止字符'\0'不会被比较。
一个字符数组被称为字符串。
声明
数组的声明语法如下 −
char stringname [size];
例如:char string[50];长度为 50 个字符的字符串
初始化
- 使用单个字符常量 −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}- 使用字符串常量 −
char string[10] = "Hello":;
访问 − 有一个控制字符串 "%s" 用于访问字符串,直到遇到‘\0’。
strstr() 函数
用于搜索子字符串是否存在于主字符串中。
它返回 s2 在 s1 中第一次出现的位置的指针。
语法
strstr() 函数的语法如下 −
strstr(mainsring,substring);
示例
以下程序展示了如何使用 strstr() 函数。
#include<stdio.h>
void main(){
char a[30],b[30];
char *found;
printf("Enter a string:
");
gets(a);
printf("Enter the string to be searched for:
");
gets(b);
found=strstr(a,b);
if(found)
printf("%s is found in %s in %d position",a,b,found-a);
else
printf("-1 since the string is not found");
}输出
当执行上述程序时,将会产生以下结果 −
Enter a string: how are you Enter the string to be searched for: you you is found in 8 position
示例 2
让我们了解有关 strstr() 函数的另一个程序。
下面是使用 strstr 库函数在一个字符串中查找另一个字符串是否作为子字符串存在的 C 语言程序。
#include<stdio.h>
#include<string.h>
void main(){
//Declaring two strings//
char mainstring[50],substring[50];
char *exists;
//Reading strings//
printf("Enter the main string :
");
gets(mainstring);
printf("Enter the sub string you would want to check if exists in main string :");
gets(substring);
//Searching for sub string in main string using library function//
exists = strstr(mainstring,substring);
//Conditions//
if(exists){
printf("%s exists in %s ",substring,mainstring);
} else {
printf("'%s' is not present in '%s'",substring,mainstring);
}
}输出
当执行上述程序时,将会产生以下结果 −
Enter the main string : TutorialsPoint c Programming Enter the sub string you would want to check if exists in main string :Programming Programming exists in TutorialsPoint c Programming
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP