Spread the love

Did you know now you can instantly catch up with your essential programming tools such as emulators and IDE`s on any device(PC/Mac/android/iOS) to remotely access your programming/testing work on high performance citrix vdi from CloudDesktopOnline. You can also add compete Office 365 suite to the same vdi by visiting O365CloudExperts.com powered with 24*7*365 days impeccable tech-support from one of the leading cloud hosting providers – Apps4Rent

Question :- Write C code to implement the strstr() function to search for a substring

Synopsis:

/* Prototype */
#include <stdio.h>

char *strstr(char *string2, char *string1);

 

Description:

The strstr function locates the first occurrence of the string string1 in the string string2 and returns a pointer to the beginning of the first occurrence.

Return Value

The strstr function returns a pointer within string2 that points to a string identical to string1. If no such sub string exists in source string a null pointer is returned.

C code to implement the strstr() function

 

#include<iostream>
using namespace std;
 
/* Driver Function */ 
char* StrStr(char *str, char *substr)
{
	  while (*str) 
	  {
		    char *Begin = str;
		    char *pattern = substr;
		    
		    // If first character of sub string match, check for whole string
		    while (*str && *pattern && *str == *pattern) 
			{
			      str++;
			      pattern++;
		    }
		    // If complete sub string match, return starting address 
		    if (!*pattern)
		    	  return Begin;
		    	  
		    str = Begin + 1;	// Increament main string 
	  }
	  return NULL;
}

/* Main Method */
int main()
{
	char s1 [] = "This is www.firmcodes.com";
   
    printf ("Returned String 1: %s\n", StrStr(s1, "firmcodes"));
 
	return 0;
}

 

Output

Write C code to implement the strstr() function to search for a substring

Suggested Reading

  1. Write a C program to reverse the words in a sentence in place
  2. Write your own trim() or squeeze() function to remove the spaces from a string
  3. Write a C program which does wildcard pattern matching algorithm