C program that replace old string with new string in array of pointer string

C program uses an array of pointers to strings str[ ]. Receive two strings str1 and str2 and check if str1 is embedded in any of the strings in str[ ]. If str1 is found, then replace it with str2.


#include<stdlib.h>
#include <stdio.h>
#include<string.h>
int f=0;//flag to trace all replacement done in one row

void newin(char *dp,int nsize,char *nw) //replacement with new elements

{for(int i=0;i<nsize;i++) *dp=*(nw+i) , dp++; }


void moveleft(char *m,int osize,int nsize)//if o size is bigger then remove extra element
{char *p;
int jump=osize-nsize;//for jump to next element in right side

   for(int i=nsize;i<strlen(m);i++) p=m+i,*p=*(m+jump+i); }



void moveright(char *m,int sp,int numel)//for move element to right and save data lost while new element or sub array insertion
{char *p;

    int start=strlen(m);//set start point at the end of array

    if(numel>start){printf("\n\t\t\tError in Right Move\n");return;}

   for(int i=start;i>=sp;i--)//loop for move each element to right

       p=(m+i+numel) ,  *p=*(m+i); }


char* rerow(char *m,char *old, char *nw) //it is used for single row replacement
{
    int osize,nsize,msize; // create integer variables for store size of arrays

    osize=strlen(old);//  find size of
    nsize=strlen(nw);  //main row and both strings
   msize=strlen(m);    // for future use in program

    char temp[msize+nsize];//create temp array for manipulation
    char *tptr=&temp[0];//create pointer for made changes in array

    while(*m!=0) //copy array to temp
{ *tptr=*m;  tptr++, *tptr=0 ,      m++;    }


char *dp=strstr(temp,old);//for get duplicate(Old) sub array Address


if(dp)//if duplicate array found
    {f=1;
     if(osize<nsize)
           moveright(dp,osize,nsize-osize);

 if(osize>nsize)
    moveleft(dp,osize,nsize);

 newin(dp,nsize,nw);

    }

char *finalp=malloc(strlen(temp)+1);//allocate dynamic memory for store new to char array to char temp array for assign main char pointer array
strcpy(finalp,temp);
return finalp;

}

int main()
{char s1[30],s2[30],*p;
char *str[]={
                 "a b c",
                 "Move a Mountain",
                 "Level a Building",
                 "Erase the Past",
                 "Make a million",
                 "...all through c!" };
  printf("\tEnter Old number : "),gets(s1);    //scanf("%[^\n]s",s1);
  printf("\n\tEnter New number : "),gets(s2);
int cmp=strcmp(s1,s2);//if old and new equal it direct go to printf funcation
if(cmp)
for(int row=0;row<6;row++)//pass evey row to funcation;
    {do{f=0;//loop for replace all old values with new in one row

        p=rerow(str[row],s1,s2);
         str[row]=p;
                    }while(f);}

for(int row=0;row<6;row++)
printf("\t\t%s\n\n",str[row]);


return 0;

}

0 Comments