两个替换函数

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值