c/c++替换字符串中的关键字(包括\等转义字符)

最近工作的时候有碰到一个问题,输入字符串中存在“\”,处理程序在读取到的时候会将其当做转义字符,导致输入字符串错误。所以产生了两个需求:1.需要将“\”替换为“\\”。2.又因为,其他需求也存在在目标字符串中寻找对应的子串,将子串替换成目标子串的需求。找了一下网上的相关替换都是针对单个char类型字符的,这种场景适合适合第一个需求,第二个需求就不合适了,所以现在写了一个同时满足两个需求的代码。在这里分享一下。

#include <iostream>
using namespace std;

std::string ReplaceAllword(const std::string& resources, const string& key, const std::string& ReplaceKey)
{
		size_t pos=0;  
		std::string temp = resources; 
		while((pos=temp.find(key,pos))!=string::npos)  
		{ 
			temp.erase(pos, key.size());//删除原有字符串
			temp.insert(pos, ReplaceKey);//插入替换字符串
			pos+= ReplaceKey.size(); //更新查询起始标志位
		} 
		return temp;
}

int main()
{
	//std::string str = "qwert99yt99us99agj";
        std::string str = "qwert\\yt\\us\\agj";
	cout<<str<<endl;
    //cout<<ReplaceAllword(str, "9", "AA")<<endl;
    cout<<ReplaceAllword(str, "\\", "\\\\")<<endl;
}

输出结果:

clh01s@ubuntu:~/test$ ./a.out 
本次为将每个“99”替换为“AA”
qwert99yt99us99agj
qwertAAytAAusAAagj
clh01s@ubuntu:~/test$ ./a.out 
本次为将每个“\”替换为“\\”
qwert\yt\us\agj
qwert\\yt\\us\\agj 
clh01s@ubuntu:~/test$ ./a.out 
本次为将每个“9”替换为“AA”
qwert99yt99us99agj
qwertAAAAytAAAAusAAAAagj

转载请注明源地址:https://blog.csdn.net/clh01s/article/details/104375939

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值