char* replace(char *source, char* sub, char *rep)
{
char* result;
char *pc1,*pc2,*pc3;
int isource,isub,irep;
isub=strlen(sub);
irep=strlen(rep);
isource=strlen(source);
if(NULL==*sub)
return strdup(source);
result=(char *)malloc(((irep>isub)?(float)strlen(source)/isub*irep+1:isource)*sizeof(char));
pc1=result;
while(*source!=NULL)
{
pc2=source;
pc3=sub;
while(*pc2==*pc3 && *pc3!=NULL && *pc2 != NULL)
pc2++,pc3++;
if(NULL==*pc3)
{
pc3=rep;
while(*pc3!=NULL)
*pc1++=*pc3++;
pc2--;
source=pc2;
}
else
*pc1++ = *source;
source++;
}
*pc1=NULL;
return result;
}
和
#include "string"
using namespace std;
std::string replace(unsigned char *sourcebuf, int sourceLen, unsigned char* findbuf, int findLen, unsigned char *repbuf, int replaceLen)
{
int pos1 = 0;
int pos2 = 0;
// you need to pass the size in bytes or any zero byte
// would terminate the std::string
std::string buf((char*)sourcebuf, sourceLen);
std::string buffind((char*)findbuf, findLen);
std::string bufrepl((char*)repbuf, replaceLen);
while ((pos2 = buf.find(buffind, pos1)) != std::string::npos)
{
// replace found buffer
buf = buf.substr(0, pos2) + bufrepl + buf.substr(pos2+findLen);
// next pos is after the replaced string to prevent from infinite loop
pos1 = pos2+replaceLen;
}
return buf;
}