
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 WorldExplanation − 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()函数的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号