C Program to Find First occurrence of String from a String

C Program to Find First occurrence of String from a String.Compiled in Dev C++

#include<stdio.h>
#include<string.h>
#include<conio.h>
int compare_string(char * , char *);
int First_Occurrence_String(char [],char []);
int string_length(char *);
main()
{

      char text[30],sreachString[30];
      int position;

      printf("\nProgram to Find First occurrence of String from a String \n");
      printf("\n-----------------------------------------------------------\n\n\n");
      printf("Enter Text : ");
      gets(text);

      printf("\nSearched String : ");
      gets(sreachString);

      position=First_Occurrence_String(text,sreachString);

      printf("\nString '%s' starts in String '%s' from Position %d",sreachString,text,position);

      getch();

      }



int First_Occurrence_String(char a[],char b[])
{
 int i,k;
 char *p,temp[string_length(b)];

 for(i=0;i<=(string_length(a)-string_length(b));i++)
 {
    p=&a[i];

    k=0;

    while(k!=string_length(b))
    {
      temp[k]=*(p+k);
      k++;

    }
    temp[k]='\0';

    if(compare_string(temp,b)==1)
    {
     break;
    }

 }
 if(i==(string_length(a)-string_length(b))+1)
 return -1;
 else
 return i;
}     





int compare_string(char *first , char *second)
     {
       while(*first!='\0')
       {
           if(*first==*second)
              {
                  first++;
                  second++;
               }
                else
              {
               return 0;
              }

       }

       return 1;

     }




 int string_length(char *a)
     {
          int count=0;
            while(*a!='\0')
            {
                           count++;
                           a++;
                           }

          return count;

     }     

Output

occurrence_STRING

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s