您好,欢迎访问一九零五行业门户网

在C/C++中的strstr()函数

strstr()函数是在“string.h”头文件中预定义的函数,用于执行字符串处理。此函数用于在主字符串(例如str1)中查找子字符串(例如str2)的第一个出现。
语法strstr()的语法如下:
char *strstr( char *str1, char *str2);
strstr()的参数是str2是我们希望在主字符串str1中搜索的子字符串
strstr()的返回值是如果在主字符串中找到了我们正在搜索的子字符串的第一个出现位置,该函数将返回该子字符串的地址指针;否则,当子字符串不在主字符串中时,它将返回一个空指针。
注意 - 匹配过程不包括空字符(‘\0’),而是在遇到空字符时停止。
示例input: str1[] = {“hello world”}str2[] = {“or”}output: orldinput: 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 foundthe 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()函数的详细内容。
其它类似信息

推荐信息