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

2023年 9月 17日 63.6k 0

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

strstr()函数是在“string.h”头文件中预定义的函数,用于执行字符串处理。此函数用于在主字符串(例如str1)中查找子字符串(例如str2)的第一个出现。

语法

strstr()的语法如下:

char *strstr( char *str1, char *str2);

登录后复制

strstr()的参数是

str2是我们希望在主字符串str1中搜索的子字符串

strstr()的返回值是

如果在主字符串中找到了我们正在搜索的子字符串的第一个出现位置,该函数将返回该子字符串的地址指针;否则,当子字符串不在主字符串中时,它将返回一个空指针。

注意 - 匹配过程不包括空字符(‘’),而是在遇到空字符时停止。

示例

Input: str1[] = {“Hello World”}
str2[] = {“or”}
Output: orld
Input: 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 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
#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()函数的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论