Pages

Friday 4 July 2014

C – strstr() function

  • strstr( ) function returns pointer to the first occurrence of the string in a given string. Syntax for strstr( ) function is given below.
char *strstr(const char *str1, const char *str2);

Example program for strstr() function in C:

  • In this program, strstr( ) function is used to locate first occurrence of the string “test” in the string ”This is a test string for testing”. Pointer is returned at first occurrence of the string “test”.
#include <stdio.h>
#include <string.h>
int main ()
{
  char string[55] ="This is a test string for testing";
  char *p;
  p = strstr (string,"test");
  if(p)
  {
    printf("string found\n" );
    printf ("First occurrence of string \"test\" in \"%s\" is"\
           " \"%s\"",string, p);
  }
  else printf("string not found\n" );
   return 0;
}

Output:

string found
First occurrence of string “test” in “This is a test string for testing” is “test string for testing”

0 comments:

Post a Comment