Wednesday 18 January 2017

Deleting first occurrence of a pattern in a given string without using strstr() :C program



#include <stdio.h>
#include <string.h>
main()
{
char T[30],P[30];
int i,k,l2,count,flag=0,j;
printf("enter a string");
scanf("%s",T);
printf("enter a pattern");
scanf("%s",P);
l2=strlen(P);
for(i=0;T[i]!='\0';i++)
{
if(T[i]==P[0]) // true only when the first character in pattern is in T
{
count=1;
for(k=i+1,j=1;P[j]!='\0';k++,j++)  // checks if remaining characters in P are in T
{
if(T[k]==P[j])
count++;
    else
        break;
}
if(count == l2) //if all the characters in P are in T then count = length of the pattern
{
flag=1;
break;
}
}
}
if(flag==1)
{
printf("\nPattern is first occured at %d\n",i);
while(T[i+l2]!= '\0')
{
T[i]=T[i+l2];
i++;
}
T[i]='\0';
printf("String after removing pattern=  %s",T);
}
else
printf("Pattern is not present in the given string");
}

OUTPUT:

No comments:

Post a Comment