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

Program : C Program to find substring

#include<stdio.h>
#include<string.h>
int search(char[],char[]);

int main()
{
char a[100],b[40];
int loc;

printf("n Enter the main string :");
gets(a);

printf("n Enter the search string :");
gets(b);

loc = search(a,b);

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

return(0);
}

int search(char a[],char b[])
{
int i,j,firstOcc;
i=0,j=0;

while(a[i]!='')
  {
     while(a[i]!=b[0] && a[i]!='')
         i++;
     if(a[i]=='')
        return(-1);     //search can not continue

    firstOcc = i;

     while(a[i]==b[j] && a[i]!='' && b[j]!='')
         {
         i++;
         j++;
         }

    if(b[j]=='')
        return(firstOcc);
    if(a[i]=='')
        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.

printf("n Enter the main string :");
gets(a);

printf("n Enter the search string :");
gets(b);

Step 2 : Calling Function and Passing Parameters

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

a = "ProgrammingLanguage"
b = "ing"

Step 3 : Function Definition :

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

while(a[i]!='')

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(a[i]!=b[0] && a[i]!='')
         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(a[i]=='')
        return(-1);     //search can not continue

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(a[i]==b[j] && a[i]!='' && b[j]!='')
         {
         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.