C Program to Replace String from a String

C Program to Replace String from a String .Compiled in Dev C++

#include<stdio.h>
#include<string.h>
#include<conio.h>
void ReplaceString(char [],char [],char [],char []);
main()
{
       char text[50],a[50],b[50],target[50];
      
      
       printf("\nProgram to Replace word from a String \n");
       printf("\n----------------------------------------------\n\n\n");
       printf("Enter Text : ");                                                   
       gets(text);    
       
       printf("\nWord To be Replaced : ");
       gets(a);
       
       printf("\nReplace By : ");
       gets(b);
       
       
       ReplaceString(text,a,b,target);
       
       printf("\nNew String : %s",target);
       
       getch();
       
       
}



void ReplaceString(char source[],char to_be_replaced[],char replaceWith[],char target[])
{
   char *p,temp[30],*t;
   int i,k,compare,pos=0,j,s;
   
   for(i=0;i<strlen(source);i++)
   {
      p=&source[i];
      k=0;
      
     
      while(k!=strlen(to_be_replaced))
      {
        temp[k]=*(p+k);
        k++;                   
      }
      
      
      temp[k]='\0';
      
    
      compare=strcmp(temp,to_be_replaced);
    
     
    
     if(compare==0)
      {
         s=0;        
         while(s!=strlen(replaceWith))
         {
           t=&replaceWith[s];
           target[pos]=*t;
           pos++;  
           s++;  
                   
         }
         
         i=i+strlen(to_be_replaced)-1;
       } 
       
      else
         {          
           target[pos]=*p;
           p++;
           pos++;
         }
         
         
                          
   }//end of for loop       
     
     target[pos]='\0';
}

Output

replace

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s