Sunday, December 12, 2010

Substring Search

//PROGRAM TO SEARCH FOR SUBSTRING IN A STRING
#include
#include
#include
#define SIZE 20
int search(char [],char []);
char* delet(char*,char*,int);
void main()
{
int ret=0,pos=0,s=0;
char str[SIZE],sub[SIZE],temp[SIZE];
clrscr();
printf("Enter the string: ");
gets(str);
printf("Enter the sub string: ");
gets(sub);
strcpy(temp,str);
while(ret!=-1)
{
ret=search(temp,sub);
if(s {
pos=ret+s*strlen(sub)+1;
printf("Substring found at position %d\n",pos);
}
s++;
if(ret!=-1)
{
strcpy(temp,delet(temp,sub,ret));
}
}
if(strcmp(temp,str)==0)
printf("Substring not found\n");
else
printf("Substring after deletion is %s\n",temp);
getch();
}
//searching substring

int search(char *a,char *b)
{
int i=0,j=0,m,n,pos;
m=strlen(a);
n=strlen(b);
while(i {
while((a[i]==b[j]) && b[j]!=0)
{
i++;
j++;
}
if(j==n)
{
pos=i-j;
return(pos);
}
else
{
i=i-j+1;
j=0;
}
}
return(-1);
}

//deleting substring
char* delet(char *a,char *b,int pos)
{
int m,i=pos;
m=strlen(b);
do
{
a[i]=a[i+m];
i++;
}
while(a[i]!='\0');
return(a);
}

No comments:

Post a Comment