strstr() in C++

C++ProgrammingServer Side Programming

The strstr() function is a predefined function in string.h. It is used to find the occurance of a substring in a string. This process of matching stops at ‘\0’ and does not include it.

Syntax of strstr() is as follows −

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

In the above syntax, strstr() finds the first occurance of string str2 in the string str1. A program that implements strstr() is as follows −

Example

 Live Demo

#include <iostream>
#include <string.h>

using namespace std;
int main() {
   char str1[] = "Apples are red";
   char str2[] = "are";
   char *ptr;
   ptr = strstr(str1, str2);

   if(ptr)
   cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1;

   else
   cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;
   return 0;
}

Output

The output of the above program is as follows −

Occurance of "are" in "Apples are red" is at position 8

In the above program, str1 and str2 are defined with the values “Apples are red” and “are” respectively. This is given below −

char str1[] = "Apples are red";
char str2[] = "are";
char *ptr;

The pointer ptr points to the first occurrence of “are” in “Apples are red”. This is done using strstr() function. The code snippet for this is given below −

ptr = strstr(str1, str2);

If the pointer ptr contains a value, then the position of str2 in str1 is displayed. Otherwise, it is displayed that there is no occurrence of ptr2 in ptr1. This is shown below −

if(ptr)
cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1;

else
cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;
raja
Published on 23-Oct-2018 11:35:04
Advertisements