Reputation: 618
I am trying to write a REPLACE
function that will replace the given
string by the required
string. 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
.
Upvotes: 0
Views: 177
Reputation: 55395
for(i=pos+reqd.length()+1,k=0; i<sizeof(arr); i++,k++)
// ^^^^^^^^^^^
// This is always the same
sizeof(arr)
is the same as sizeof(char*)
, a compile-time constant value. You need to keep the size of a dynamically allocated array yourself (or, better yet, simply use std::string
instead).
Upvotes: 1
Reputation: 12715
I don't think it is a good idea to mix std::string with char arrays. Following should work:
string REPLACE(string src,string reqd,string given)
{
int pos = FIND(src,given);
src.replace( pos, given.size(), reqd );
return src;
}
Upvotes: 1
Reputation: 3934
Assuming you do not want to re-invent the wheel:
string REPLACE(string src,string reqd,string given)
{
string str(src);
size_t pos = str.find(given);
if(pos == std::string::npos)
return "";
str.replace(pos, given.length(), reqd);
return str;
}
Upvotes: 0