That code is optimised until it's not straight forward any more, so I'll give you the simplified version that follows what I posted earlier:
#include <cstring>
char* DuplicateString(const char* Source)
{
size_t SourceLen = std::strlen(Source);
char* NewString = new char[ SourceLen + 1 ];
std::memcpy(NewString, Source, SourceLen + 1);
return NewString;
}
char* ReplaceString(const char* Source, const char* Search, const char* Replace)
{
size_t SourceLen = std::strlen(Source); // Get the source string length
size_t SearchLen = std::strlen(Search); // Get the search string length
size_t ReplaceLen = std::strlen(Replace); // Get the replacement string length
// Locate the search string in the source string
char* Found = std::strstr( Source, Search );
if (! Found)
{
// Search string not found, so simply duplicate the string
return DuplicateString(Source);
}
size_t FoundPos = Found - Source;
// Allocate a buffer of (source_size-search_size+replacement_size+1)
char* NewString = new char[ SourceLen - SearchLen + ReplaceLen + 1];
size_t WritePos = 0;
// Copy from the source string to the buffer up to but not including the search string
if (FoundPos)
{
std::memcpy(NewString, Source, FoundPos);
WritePos += FoundPos;
}
// Append the replacement string to the buffer
std::memcpy(NewString + WritePos, Replace, ReplaceLen);
WritePos += ReplaceLen;
// Append from the end of the search string in the source string to the buffer
std::strcpy(NewString + WritePos, Found + SearchLen);
return NewString;
}
That can be used like so:
#include <iostream>
int main()
{
char* s = ReplaceString("Hello World", "o W", "ooo Wooo");
std::cout << s << '\n';
delete[] s;
}
Remember to free the returned string at some point.
Also, this code was written using the GCC compiler, so you may need to remove the 'std::' part from some of the functions or replace that with a leading underscore or two to get it to compile under VC++. If you have problems with that, I'll clean it up tomorrow.