Friday, November 23, 2012

WRITE A C PROGRAM TO INPUT STRINGS S1 AND S2 OF LENGTHS N AND M RESPECTIVELY SUCH THAT M < N. FIND THE POSITION OF FIRST OCCURENCE OF S2 IN S1



/* WRITE A C PROGRAM TO INPUT STRINGS S1 AND S2 OF LENGTHS N AND 
    M RESPECTIVELY SUCH THAT M < N. FIND THE POSITION OF FIRST 
    OCCURENCE OF S2 IN S1
*/
#include<stdio.h>
char Ms[50],Ss[30];
main()
{
 char *ptr1,*ptr2;
 int pos;
 clrscr();
 ptr1=Ms;
 printf("\n ENTER THE FIRST STRING \n");
 string_read(ptr1);
 ptr2=Ss;
 printf("\n ENTER THE SECOND STRING \n");
 string_read(ptr2);
 pos=string_compare(Ms,Ss);
 if(pos!=0)
 {
  printf("\n \"%s\" is found at \"%s\" in the position %d.",Ss,Ms,pos);
 }
else
   printf("\n %s is not found in %s",Ss,Ms);
   getch();
}

/* FUNCTION TO ACCEPT A STRING */
string_read(char *ptr)
{
 while((*ptr=getchar())!='\n')
  ptr++;
  *ptr='\0';
}
/* FUNCTION TO COMPARE THE STRING */
string_compare(char Ms[], char Ss[])
{
 int i,j,k;
 for(i=0;Ms[i]!='\0';i++)
 {
  for(j=i,k=0;Ss[k]&&Ms[j]==Ss[k];j++,k++);
  if(Ss[k]=='\0' && k>0)
  return(i+1);
 }
 return(0);
}
/*
            =====OUT PUT=====

      1. ENTER THE FIRST STRING
            bharath

             ENTER THE SECOND STRING
            rath

             "rath" is found at "bharath" in the position 4.

      2. ENTER THE FIRST STRING
            JAYANTH

             ENTER THE SECOND STRING
            R        

             R is not found in JAYANTH

*/







0 comments:

Post a Comment