strstr() Function in C: Finding Substring in String

Rumman Ansari   Software Engineer   2024-07-05 04:26:09   7566  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

strstr() function returns pointer to the first occurrence of the string in a given string. Syntax for strstr( ) function is given below.

Syntax

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

Returns

The strstr() function returns a pointer to the first occurrence in the string pointed to by str1 of the string pointed to by str2. It returns a null pointer if no match is found.

Program 1

This program displays the message is is a test:

#include 
#include 
void main(void)
{
	char *poin;
	poin = strstr("this is a test", "is");
	printf(poin);
 
}

Output

is is a test 

Program 2

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 
#include 
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 "tes
t string for testing"