题目要求:编写一个函数,接受三个string参数s,oldVal和newVal。使用迭代器及insert和erase函数将s中所有oldVal替换为newVal。测试你的程序,用它替换通用的简写形式,如,将"tho"替换为"though",将"thru"替换为"though"。

#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std; void find_replace(string s, string oldValue, string newValue)
{
if (s.empty() || oldValue.empty() || newValue.empty())
{
cout << "Error" << endl;
return;
}
if (s.size() < newValue.size())
{
cout << "Error" << endl;
return;
} string word;
vector<string>vec; //分割string
istringstream stream(s);
{
while(stream >> word)
vec.push_back(word);
} vector<string>::iterator it1 = vec.begin(); while (it1 != vec.end())
{
if (*it1 == oldValue)
{
string::iterator it2 = (*it1).begin();
it2 = (*it1).erase(it2, it2+oldValue.size());
(*it1).insert(it2, newValue.begin(), newValue.end());
}
else
{
string::iterator it3 = (*it1).begin();
string::iterator it4 = oldValue.begin();
while (it3 != (*it1).end())
{
if ((*it3) == (*it4))
{
string sub = (*it1).substr(it3-(*it1).begin(), oldValue.size());
if (sub == newValue)
{
unsigned offset = it3 - (*it1).begin();
it3 = (*it1).erase(it3, it3+oldValue.size());
(*it1).insert(it3, newValue.begin(), newValue.end());
it3 = (*it1).begin() + offset + newValue.size() - 1;
}
}
it3++;
}
}
it1++;
} for (auto i = vec.begin(); i != vec.end(); i++)
cout << *i << endl; } int main()
{
//略 return 0;
}

  

05-11 22:00