Using strstr in c – strstr C Library Function

Using strstr in c: The function char *strstr(const char *str1, const char *str2); searches for the first occurrence of string str2 in string str1, or returns NULL pointer if str2 is not found in str1.

Function prototype of strstr

char *strstr(const char *str1, const char *str2);
  • str1 : A pointer to a string to be scanned.
  • str2 : A pointer to a smaller string to be searched with-in str1.

Return value of strstr

Strstr c: This function returns a pointer to the first occurrence in str1 of the entire sequence of characters specified in str2, or returns NULL pointer if str2 is not found in str1.

C program using strstr function

Strstr in c: The following program shows the use of strstr function to search a substring inside a string.

strstr C Library Function

#include <stdio.h>
#include <string.h>
#include <conio.h>
 
int main(){
   char string[100], pattern[100];
   char *ptr;
    
   printf("Enter a string\n");
   scanf("%s", &string);
   printf("Enter string to search\n");
   scanf("%s", &pattern);
    
   ptr = strstr(string, pattern);
    
   if(NULL == ptr){
       printf("%s not found\n",pattern);
   } else {
       printf("%s found at index %d\n",pattern, ptr-string);
   }
    
   getch();
   return(0);
}

Output

Enter first string
JAHGDSTECHWEHJG
Enter string to search
TECH
TECH found at index 6
Enter first string
Cprogramming
Enter string to search
TECH
TECH not found