64,637
社区成员
发帖
与我相关
我的任务
分享
#include <string>
using std::string;
#include <iostream>
//s的大小如果直接初始化的话 capacity 和 size是一样大小的 , 也就是说 newVal 只要 比 oldVal 长 , 下面代码就是错的。
//因此在初始化完string以后 , reserve给string足够的capacity
void Replace(string& s, const string& oldVal, const string& newVal)
{
for ( string::iterator beg = s.begin(); std::distance(beg, s.end()) >= std::distance(oldVal.begin(), oldVal.end()); ) //原串的比较部分必须比子串的长度长才行
{
if(string(beg, beg + oldVal.size()) == oldVal)
{
string::iterator pre = beg-1; //将pre指向 beg 的前一个 , 不超过capacity的插入 , 只会使 插入 / 删除位置后的迭代器失效 , pre 不失效
beg = s.erase(beg, beg + oldVal.size());
s.insert(beg, newVal.begin(), newVal.end());
std::advance(pre, newVal.size()); //将pre指向 插入字符串的最后一个字符
}
++beg;
}
}
int main()
{
{
string str("Tod drive straight thru is a foolish,thocourageousact.");
std::cout << str.capacity() << " " << str.size()<< std::endl; //打印输出是一样大的
str.reserve(1024); //至关重要
Replace(str, "thru", "through");
std::cout << str << std::endl;
//Replace(str, "tho", "though");
}
getchar();
return 0;
}
#include <string>
#include <iostream>
using namespace std;
void Replace(string s, string oldVal, string newVal)
{
auto sit = s.begin();
while(sit!=s.end())
{ auto oldit = oldVal.begin();
while(sit!=s.end() && oldit!=oldVal.end() && *sit==*oldit)
{
++sit;
++oldit;
}
if (oldit==oldVal.end())
{
sit = s.erase(sit - oldVal.size(), sit);
sit = s.insert(sit, newVal.begin(), newVal.end());
sit += newVal.size();
}
else if (sit == s.end()) return;
else ++sit;
}
return;
}
int main()
{
string txt{"abc abc abc bcd efg efg hi hi"};
Replace(txt, "abc", "ABC");
for(auto t: txt)
cout << t << ends;
return 0;
}