Thursday 6 January 2011

First version of my custom-written C++ string replacement function to be more like Perl's

Here's the code. Use it how you like.

I don't know what'll happen with any inputs a blank string, but try not to pass blank strings in.

string myreplaceall(string input,string match,string replace)
{
//first find out how many matches in input
long i;
long mysize = 0;
for (i = 0; i < input.size(); i++)
{
if (!strncmp(input.c_str()+i,match.c_str(),match.size()))
{
i += match.size()-1;
mysize++;
}
}

//mysize tells us how many matches there are

//first deduct the match strings * mysize
long finallen = input.size() - mysize * (match.size());
//add on the replace strings * mysize
finallen += mysize * (replace.size());

//allocate a string of finallen
char *outbuffer;
outbuffer = (char *)malloc(finallen+1);

string retval;

long ptr = 0;

//copy text into outbuffer
//either a single letter, or replace the 'match' string with the 'replace' string
for (i = 0; i < input.size(); i++)
{
if (!strncmp(input.c_str()+i,match.c_str(),match.size()))
{
i += match.size()-1;
long j;
for (j = 0; j < replace.size(); j++)
{
outbuffer[ptr+j] = replace[j];
}
ptr += replace.size();
}
else
{
outbuffer[ptr] = input[i];
ptr++;
}
}

//terminate string
outbuffer[ptr] = 0;
//make string of return value
retval = outbuffer;
//free outbuffer memory
free(outbuffer);

//return replaced string
return retval;
}

No comments: