码迷,mamicode.com
首页 > 编程语言 > 详细

C++primer 9.43

时间:2016-09-15 09:45:30      阅读:300      评论:0      收藏:0      [点我收藏+]

标签:

题目要求:编写一个函数,接受三个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;
}

  

C++primer 9.43

标签:

原文地址:http://www.cnblogs.com/KennyRom/p/5874278.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!