用stl替换字符串中所有匹配的子串_实现字符串的查找和替换

在字符串中查找目标字符串并将其替换为指定字符串,返回替换的次数。接口为

int find_str_replace(char *&str,const char *find_str,const char *replace_str)

将str中所有find_str替换为replace_str。要求不利用STL,c实现代码如下:

#include

#include

#include

//查找str从fromwhere开始第一次出现sub_str的位置

int find(const char *str,const char *sub_str,int fromwhere)

{

int len=strlen(str);

int len_f=strlen(sub_str);

for(int i=fromwhere;i=len_f;i++)

{

int k=i;

int j=0;

while(j

{

if(str[k]==sub_str[j])

{

k++;

j++;

}

else

break;

}

if(j==len_f)

{

return i;

}

}

return -1;

}

//替换fromwhere处的find_str为replace_str

void replace(char *&str,const char *find_str,const char *replace_str,int fromwhere)

{

int len=strlen(str);

int len_f=strlen(find_str);

int len_r=strlen(replace_str);

char *p=(char*)malloc(len+len_r-len_f);

memset(p,0,len+len_r-len_f);

strncpy(p,str,fromwhere);

strcat(p,replace_str);

strcat(p,str+fromwhere+len_f);

str=p;

}

//在str中将所有find_str替换为repalce_str;

int find_str_replace(char *&str,const char *find_str,const char *replace_str)

{

int num=0;

int len=strlen(str);

int len_r=strlen(replace_str);

int k=0;

while(k

{

int pos=find(str,find_str,k);

if(pos==-1)break;

else

{

replace(str,find_str,replace_str,pos);

k=pos+len_r;

num++;

}

}

return num;

}

int main()

{

char *a="123456783450987634243453";

char *b="345";

char *c="ABCD";

int num=find_str_replace(a,b,c);

printf("%s\n",a);

printf("%d",num);

return 0;

}若使用c++并利用STL,代码极其简单:

#include

#include

using namespace std;

int find_str_replace(string &str,string find_str,string replace_str)

{

int num=0;

int len_f=find_str.length();

int len_r=replace_str.length();

int pos=str.find(find_str,0);

while(pos!=string::npos)

{

str.replace(str.begin()+pos,str.begin()+pos+len_f,replace_str);

pos=pos+len_r;

pos=str.find(find_str,pos);

num++;

}

return num;

}

int main()

{

string a="123456783450987634243453";

string b="345";

string c="ABCD";

int num=find_str_replace(a,b,c);

printf("%s\n",a.c_str());

printf("%d",num);

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值