C++ Standard Library C++ STL Library

C++ <cstring> - strstr() Function



The C++ <cstring> strstr() function is used to find the first occurrence of the byte string str2 in the byte string pointed to by str1. The terminating null characters are not compared.

The function returns pointer to the first occurrence of str2 in str1, or null pointer if str2 is not found in str1.

Syntax

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

Parameters

str1 Specify pointer to the null-terminated byte string to be searched in.
str2 Specify pointer to the null-terminated byte string to be searched for.

Return Value

Returns pointer to the first occurrence of str2 in str1, or null pointer if str2 is not found in str1.

Example:

The example below shows the usage of strstr() function.

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
  char MyStr[100] = "To be, or not to be, that is the question.";
  char * search;
  
  //searching for first occurrence of "be"
  search = strstr(MyStr, "be");

  //displaying the result
  if(search != NULL)
    cout<<"First occurrence of 'be' starts at: "
        <<(search-MyStr+1)<<"\n";
  else
    cout<<"Not Found."<<"\n";
 
  return 0;
}

The output of the above code will be:

First occurrence of 'be' starts at: 4

❮ C++ <cstring> Library