Facebook Page Twitter Page LinkedIn Page
× C Standard Library


The C <string.h> 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 <stdio.h>
#include <string.h>
 
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)
    printf("First occurrence of 'be' starts at: %ld\n",
           (search-MyStr+1));
  else
    printf("Not Found.\n");
 
  return 0;
}

The output of the above code will be:

First occurrence of 'be' starts at: 4

❮ C <string.h> Library

5