
strstr()函数是在“string.h”头文件中预定义的函数,用于执行字符串处理。此函数用于在主字符串(例如str1)中查找子字符串(例如str2)的第一个出现。
strstr()的语法如下:
char *strstr( char *str1, char *str2);
str2是我们希望在主字符串str1中搜索的子字符串
如果在主字符串中找到了我们正在搜索的子字符串的第一个出现位置,该函数将返回该子字符串的地址指针;否则,当子字符串不在主字符串中时,它将返回一个空指针。
立即学习“C++免费学习笔记(深入)”;
注意 - 匹配过程不包括空字符(‘\0’),而是在遇到空字符时停止。
Input: str1[] = {“Hello World”}
str2[] = {“or”}
Output: orld
Input: str1[] = {“tutorials point”}
str2[] = {“ls”}
Output: ls point
实时演示
#include <string.h>
#include <stdio.h>
int main() {
char str1[] = "Tutorials";
char str2[] = "tor";
char* ptr;
// Will find first occurrence of str2 in str1
ptr = strstr(str1, str2);
if (ptr) {
printf("String is found\n");
printf("The occurrence of string '%s' in '%s' is '%s'", str2, str1, ptr);
}
else
printf("String not found\n");
return 0;
}
如果我们运行上面的代码,它将生成以下输出 -
String is found The occurrence of string 'tor' in 'Tutorials' is 'torials
现在,让我们尝试另一个strstr()的应用
我们也可以使用这个函数来替换字符串的某个部分,例如,如果我们想要在找到第一个子字符串str2之后替换字符串str1。
Input: str1[] = {“Hello India”}
str2[] = {“India”}
str3[] = {“World”}
Output: Hello World
Explanation − Whenever the str2 is found in str1 it will be substituted with the str3
实时演示
#include <string.h>
#include <stdio.h>
int main() {
// Take any two strings
char str1[] = "Tutorialshub";
char str2[] = "hub";
char str3[] = "point";
char* ptr;
// Find first occurrence of st2 in str1
ptr = strstr(str1, str2);
// Prints the result
if (ptr) {
strcpy(ptr, str3);
printf("%s\n", str1);
} else
printf("String not found\n");
return 0;
}
如果我们运行上面的代码,它将生成以下输出 -
Tutorialspoint
上面即是在C/C++中的strstr()函数的内容了,文章的版权归原作者所有,如有侵犯您的权利,请及时联系本站删除,更多相关strstr的资讯,请关注收藏西西下载站。