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


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

语法

strstr() 的语法如下:

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

strstr() 的参数为

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

strstr() 的返回值为

如果在主字符串中找到我们正在搜索的子字符串,则此函数返回该子字符串第一次出现的地址指针;否则,如果子字符串不存在于主字符串中,则返回空值。

注意 - 匹配过程不包括空字符('\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

解释 - 每当在 str1 中找到 str2 时,它将被替换为 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

更新于: 2020年1月20日

613 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.