C Program to Find Substring Of String Without Using Library Function !!!

   

Program : C Program to find substring

#include
#include

int search(char[], char[]);

int main() {
   int loc;

   char source[] = "maharashtra";
   char target[] = "sht";

   loc = search(source, target);

   if (loc == -1)
      printf("\nNot found");
   else
      printf("\nFound at location %d", loc + 1);

   return (0);
}

int search(char src[], char str[]) {
   int i, j, firstOcc;
   i = 0, j = 0;

   while (src[i] != '\0') {

      while (src[i] != str[0] && src[i] != '\0')
         i++;

      if (src[i] == '\0')
         return (-1);

      firstOcc = i;

      while (src[i] == str[j] && src[i] != '\0' && str[j] != '\0') {
         i++;
         j++;
      }

      if (str[j] == '\0')
         return (firstOcc);
      if (src[i] == '\0')
         return (-1);

      i = firstOcc + 1;
      j = 0;
   }
}

Explanation Of Program :

If you look at the above program then you will find this program approach bit difficult but still it is perfect program.

Step 1 : Accepting the Input

Accepting input is state forward step.

char source[] = "maharashtra";
char target[] = "sht";

Step 2 : Calling Function and Passing Parameters

We are calling user defined function , Consider following strings are entered by the user -

char source[] = "maharashtra";
char target[] = "sht";

Step 3 : Function Definition :

We are iterating inside while loop upto end of string. Variable ‘i’ is used to iterate String 1.

while (src[i] != '\0') {

We are searching String 2 in String 1 so we are checking whether First Character of String 2 is present inside String 1 or not.

while (src[i] != str[0] && src[i] != '\0')
         i++;

We are moving inside String 1 as we don’t find first character of String 2 in String 1. The while loop will be terminated because of two conditions i.e End of String 1 or Character Found.
If above while loop is terminated because of coinsurance of End Character then we can say that String2 is not a Substring of String1.

if (src[i] == '\0')
         return (-1);

Save Value of ‘i’ inside another value to track first occurrence of Substring. Now we are checking whether all characters from string2 are present inside string1 or not.

while (src[i] == str[j] && src[i] != '\0' && str[j] != '\0') {
	 i++;
	 j++;
}

Now again above loop can be terminated using 3 conditions -

  1. End of String 1
  2. End of String 2
  3. Characters are unequal

If Loop gets terminated due to end of string2 then we can say that string2 is substring of string1.