strstr() function in C/C++

CC++Server Side ProgrammingProgramming

strstr() function is a predefined function in “string.h” header file which is used for performing string handling. This function is used to find the first occurrence of a substring let’s say str2 in the main string let’s say str1.

Syntax

Syntax of strstr() is as follows −

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

Parameters of strstr() are

str2 is the substring which we wish to search in the main string str1

Return value of strstr() is

This function returns the address pointer of the first occurrence of the substring which we are searching if found in the main string, else it will return a null when the substring is not present in the main string.

Note − The process of matching does not include the null character(‘\0’), rather the function stops when it encounters null character

Example

Input: str1[] = {“Hello World”}
str2[] = {“or”}
Output: orld
Input: str1[] = {“tutorials point”}
str2[] = {“ls”}
Output: ls point

Example

 Live Demo

#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;
}

Output

If we run the above code it will generate the following output −

String is found
The occurrence of string 'tor' in 'Tutorials' is 'torials

Now, let’s try an another application of strstr()

We can also use this function to substitute a certain part of a string, for example, if we want to substitute the string str1 after the first occurrence of its substring str2 is found.

Example

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

Example

 Live Demo

#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;
}

Output

If we run the above code it will generate the following output −

Tutorialspoint
raja
Published on 20-Jan-2020 11:40:22
Advertisements