C language question Consider the function substring whose C

C language question

Consider the function substring (), whose C99 prototype follows: bool subString (char *haystack, char *needle); The purpose of the function is to determine if the character string pointed to by needle is a substring of the character string pointed to by haystack. The function returns true if needle is a substring of haystack (i.e. needle completely appears within haystack), and false otherwise. You may assume that both haystack and needle are valid pointers to strings. Write the function subString () in C99. Do not simply call the similar C99 function strstr ().

Solution

Please find the function below:

bool subString(char *haystack, char *needle){
   bool isSubString=false;
   int len1=strlen(haystack);
   int len2=strlen(needle);
  
   //firstLoc is needed to find the 1st occurrence of the matching character in the source string
   int firstLoc,counter1,counter2;
  
   //temporary pointers to store the initial pointers for the strings
   char *temp=haystack;
   char *temp2=needle;
   counter1=counter2=0;
  
   //iterate again and again to find the next matching occurrence in haystack until the end of haystack is reached
   while(counter1<len1){
   while(*temp!=*needle&&counter1<len1){
   temp++;
  
   counter1++;
  
   }
   //if end of source string is reached it implies that given string isn\'t a substring
   if(counter1==len1){
   isSubString=false;
   break;
   }
   firstLoc=counter1;
  
   //keep matching the characters of both the strings until either one of them reaches end or an unmatching character is found
   while(*temp==*temp2&&counter1!=len1&&counter2!=len2){
   counter1++;
   counter2++;
   temp++;
   temp2++;
   }
  
   //if end of given string(needle) is reached, it implies that it is a substring
   if(counter2==len2){
   isSubString=true;
   break;
   }
  
   //if end of source(haystack) is reached and needle has still not reached at end, it implies that needle isn\'t a substring of haystack
   if(counter1==len1){
   isSubString=false;
   break;
   }
   counter1=firstLoc+1;
   counter2=0;
   temp2=needle;
   temp=haystack;
   for(int i=0;i<counter1;i++)
   temp++;
  
   }
   return isSubString;

}

C language question Consider the function substring (), whose C99 prototype follows: bool subString (char *haystack, char *needle); The purpose of the function
C language question Consider the function substring (), whose C99 prototype follows: bool subString (char *haystack, char *needle); The purpose of the function

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site