最近工作的时候有碰到一个问题,输入字符串中存在“\”,处理程序在读取到的时候会将其当做转义字符,导致输入字符串错误。所以产生了两个需求: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