Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project: C Program #12

Sunday, March 10, 2013

C Program #12


/*A program that will search a line of given text for a particular pattern or substring. If the pattern is found it is to be replaced by another given pattern*/
#include<stdio.h>
#include<string.h>
int replace(char *,char[],char[],int,int,int,int);
int main()
{
char line[200],srch[15],rep[15];
int i,j,l_line,l_srch,l_rep,pos;
printf("\n Enter the line:");
gets(line);
l_line=strlen(line);
printf("\n Enter the pattern to be replaced:");
gets(srch);
l_srch=strlen(srch);
printf("\n Enter the pattern to be place:");
gets(rep);
l_rep=strlen(rep);
for(i=0;i<=(l_line-l_srch);i++)
            {
                        for(j=0;j<l_srch;j++)
                                    if(line[i+j]==srch[j])
                                                continue;
                                    else
                                                break;
                                    if(j==l_srch)
                                                {
                                                pos=i;
                                                l_line=replace(line,srch,rep,pos,l_line,l_srch,l_rep);
                                                }

            }
printf("\n String after replacement:\n");
puts(line);
return 0;
}
int replace(char *line,char srch[],char rep[],int pos,int l_line,int l_srch,int l_rep)
{
int i,m=0;
            if(l_rep-l_srch>=0)
                        {
                        for(i=l_line-1;i>=(pos+l_srch);i--)
                                                            {
                                                            line[i+l_rep-l_srch]=line[i];
                                                            }
                        line[l_line+l_rep-l_srch]='\0';
                        for(i=pos,m=0;i<l_rep+pos;i++,m++)
                                    {line[i]=rep[m];}
                        return(strlen(line));
                        }
            else if(l_rep-l_srch<0)
                        {
                        for(i=(pos+l_srch),m=0;i<=l_line-1;i++,m++)
                                                            {
                                                            line[pos+l_rep+m]=line[i];
                                                            }
                        line[l_line-l_srch+l_rep]='\0';
                        for(i=pos,m=0;i<pos+l_rep;i++,m++)
                                    {line[i]=rep[m];}
                        return(strlen(line));
                        }
   else
   return(l_line);
}

No comments:

Post a Comment