C program to find and replace a string in a sentence

C Program for finding a pattern in a sentence and replace it with another string.
//main string: Manoj Kumar Sahu
//string to be found and replaced: uma
//new string to be replaced with uma: UMA
//resultant string: Manoj KUMAr Sahu
#include<stdio.h>
#include<string.h>
#include<malloc.h>
char* fr(char* str, char* old, char* new)
{
int count=0, i=0;
char* ret;
int lenold = strlen(old);
int lennew = strlen(new);
for(i=0;str[i]!='\0';i++)
{
if(strstr(&str[i],old)==&str[i])
{
count=count+1;
lenold=lenold-1;
}
else{}
}
ret=(char*)malloc(i+count*(lennew-lenold));
i=0;
while(*str)
{
    //if(strstr(&str[i],old)=&str[i])//l value required
    if(strstr(str,old)==str)
    {
    //copy
    strcpy(&ret[i],new);
    i=i+lennew;
    str=str+lenold;
    }
    else
    {
    ret[i]=*str;
    i++;   
    str++;
    }
}
return ret;
}
int main()
{
char str[]="manoj kumar sahu";
char old[]="uma";
char new[]="UMA";
char *result=fr(str,old,new);
printf("resltanc string=%s\n",result);
return 0;
}

No comments:

Post a Comment