I am trying to write a REPLACE function that will replace the given string by the requiredstring. When I am dry running the function on paper, everything seems to be fine but while executing, it's not giving the correct output. The code is as follows:-
string REPLACE(string src,string reqd,string given)
{
int i,j,k;
int pos = FIND(src,given);
if(pos==-1)
return "";
else
{
char *arr = new char[src.length()+reqd.length()-given.length()]; // creating the array that will hold the modified string
for(i=0;i<pos;i++)
arr[i] = src[i]; // copying the initial part of the string
for(i=pos,j=0;i<pos+reqd.length()+1&&j<reqd.length();i++,j++)
arr[i] = reqd[j]; // copying the required string into array
for(i=pos+reqd.length()+1,k=0;i<sizeof(arr);i++,k++)
arr[i] = src[pos+given.length()+k]; // copying the remaining part of source string into the array
return arr;
}
}
Here the FIND is also written by me and has been tested in many cases. I don't see any error in FIND.
std:stringgood enough? You also leak memory every time you call this function.std::string arr(src.length()+reqd.length()-given.length(), 0);.std::stringis a dynamic container that can change its size.