C/C++ 字符串replace替换函数

来源:互联网 发布:淘宝其他物流是什么 编辑:程序博客网 时间:2024/06/04 18:51
基于char* 

char*replace(char*src, char*sub, char*dst)
{
int pos =0;
int offset =0;
int srcLen, subLen, dstLen;
char*pRet = NULL;


srcLen = strlen(src);
subLen = strlen(sub);
dstLen = strlen(dst);
pRet = (char*)malloc(srcLen + dstLen - subLen +1);//(外部是否该空间)if (NULL != pRet)
{
pos = strstr(src, sub) - src;
memcpy(pRet, src, pos);
offset += pos;
memcpy(pRet + offset, dst, dstLen);
offset += dstLen;
memcpy(pRet + offset, src + pos + subLen, srcLen - pos - subLen);
offset += srcLen - pos - subLen;
*(pRet + offset) ='\0';
}
return pRet;
}

说明:

//参数,src 字符串源,sub想要替换的字符串,dst,用来替换的字符串
char*replace(char*src, char*sub, char*dst)
{
//记录当前指针位置
int pos =0;
//记录偏移

int offset =0;
//字符串长度
int srcLen, subLen, dstLen;
//返回内容

char*pRet = NULL;


//求得各字符串长度

srcLen = strlen(src);
subLen = strlen(sub);
dstLen = strlen(dst);
//申请替换后的字符串缓冲区。用dst替换sub,所以应该是srclen-sublen+dstlen,+1流出'\0'位置
pRet = (char*)malloc(srcLen + dstLen - subLen +1);//(外部是否该空间)if (NULL != pRet)
{
//strstr查找sub字符串出现的指针。该指针减去src地址。得到相对位置
pos = strstr(src, sub) - src;
//拷贝src字符串,从首地址开始,pos个字符。
memcpy(pRet, src, pos);
//增加偏移位置到pos
offset += pos;
//拷贝dst到返回内容中。
memcpy(pRet + offset, dst, dstLen);
//重新定位偏移
offset += dstLen;
//拷贝src中,sub字符串后面的字符串到pRet中
memcpy(pRet + offset, src + pos + subLen, srcLen - pos - subLen);
//重新定位偏移
offset += srcLen - pos - subLen;
//最后添加字符串结尾标记'\0'
*(pRet + offset) ='\0';
}
//返回新构造的字符串
return pRet;
}

基于C++ 的string类

inline void CSreplace(std::string& s1,std::string& s2,std::string& s3,int count){ std::string::size_type pos=0; std::string::size_type a=s2.size(); std::string::size_type b=s3.size(); if(count == -1){ while((pos=s1.find(s2,pos))!=std::string::npos) { s1.replace(pos,a,s3); pos+=b; } } else{ int c = 0; while((pos=s1.find(s2,pos))!=std::string::npos) { s1.replace(pos,a,s3); pos+=b; if(++c == count) return; } }}

0 0
原创粉丝点击