What is strstr() Function in C language?


The C library function char *strstr(const char *haystack, const char *needle) function finds the first occurrence of the substring needle in the string haystack. The terminating '\0' characters are not compared.

An array of characters is called a string.

Declaration

The syntax for declaring an array is as follows −

char stringname [size];

For example − char string[50]; string of length 50 characters

Initialization

  • Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
  • Using string constants −
char string[10] = "Hello":;

Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.

The strstr() Function

  • It is used to search whether a substring is present in the main string or not.

  • It returns pointer to first occurrence of s2 in s1.

Syntax

The syntax for strstr() function is as follows −

strstr(mainsring,substring);

Example

The following program shows the usage of strstr() function.

 Live Demo

#include<stdio.h>
void main(){
   char a[30],b[30];
   char *found;
   printf("Enter a string:
");    gets(a);    printf("Enter the string to be searched for:
");    gets(b);    found=strstr(a,b);    if(found)       printf("%s is found in %s in %d position",a,b,found-a);    else       printf("-1 since the string is not found"); }

Output

When the above program is executed, it produces the following result −

Enter a string: how are you
Enter the string to be searched for: you
you is found in 8 position

Example 2

Let’s see another program on strstr() function.

Given below is a C program to find, if a string is present in another string as substring by using strstr library function −

 Live Demo

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring two strings//
   char mainstring[50],substring[50];
   char *exists;
   //Reading strings//
   printf("Enter the main string : 
");    gets(mainstring);    printf("Enter the sub string you would want to check if exists in main string :");    gets(substring);    //Searching for sub string in main string using library function//    exists = strstr(mainstring,substring);    //Conditions//    if(exists){       printf("%s exists in %s ",substring,mainstring);    } else {       printf("'%s' is not present in '%s'",substring,mainstring);    } }

Output

When the above program is executed, it produces the following result −

Enter the main string : TutorialsPoint c Programming
Enter the sub string you would want to check if exists in main string :Programming
Programming exists in TutorialsPoint c Programming

Updated on: 19-Mar-2021

717 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements