
strstr()函数是在“string.h”头文件中预定义的函数,用于执行字符串处理。此函数用于在主字符串(例如str1)中查找子字符串(例如str2)的第一个出现。
语法
strstr()的语法如下:
char *strstr( char *str1, char *str2);
strstr()的参数是
str2是我们希望在主字符串str1中搜索的子字符串
strstr()的返回值是
如果在主字符串中找到了我们正在搜索的子字符串的第一个出现位置,该函数将返回该子字符串的地址指针;否则,当子字符串不在主字符串中时,它将返回一个空指针。
立即学习“C++免费学习笔记(深入)”;
注意 – 匹配过程不包括空字符(‘ ’),而是在遇到空字符时停止。
示例
Input: str1[] = {“Hello World”}str2[] = {“or”}Output: orldInput: str1[] = {“tutorials point”}str2[] = {“ls”}Output: ls point
示例
实时演示
#include #include 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 foundn"); printf("The occurrence of string '%s' in '%s' is '%s'", str2, str1, ptr); } else printf("String not foundn"); 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 #include 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("%sn", str1); } else printf("String not foundn"); return 0;}
输出
如果我们运行上面的代码,它将生成以下输出 –
Tutorialspoint
以上就是在C/C++中的strstr()函数的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1445361.html
微信扫一扫
支付宝扫一扫