C++ Primer练习——替换单词(多种做法,注意细节!)

题目:编写一个函数,接受三个string参数s、oldval、newval。使用迭代器+insert+erase函数将s中所有oldval替换为newval。

注意

1、不要比较指向不同的迭代器

2、下标遍历寻找子串用substr成员函数,迭代器遍历寻找子串利用两个迭代器初始化string

方法一(迭代器+erase+insert):

#include<iostream>
#include<string>
using namespace std;
void Replace(string& s, const string& oldval, const string& newval)
{
	for (auto i = s.begin(); distance(i, s.end()) >= distance(oldval.begin(), oldval.end());)
	{
		if (string(i,i + oldval.size() ) == oldval)   //注意两个迭代器初始化string
		{
			i = s.erase(i, i + oldval.size());
			i = s.insert(i, newval.begin(), newval.end());
			advance(i, newval.size()); //因为string中insert函数返回的是插入的第一个字符的迭代器,所有要加上newval.size()
		}
		else
			++i;
	}
}
int main()
{
	string str( "To drive straight thru is a foolish, tho courageous act." );
	Replace(str, "tho", "though");
	Replace(str, "thru", "through");
	cout << str << endl;
	system("pause");
}

方法二(迭代器+replace):

#include<iostream>
#include<string>
using namespace std;
void Replace(string& s,const string& oldval,const string& newval)
{
	for (auto i = s.begin(); distance(i, s.end()) >= distance(oldval.begin(), oldval.end());)
	{
		if (string(i, i + oldval.size()) == oldval)
		{
			s.replace(i, i + oldval.size(), newval);
			i = i + newval.size() - 1;    //注意:当s里的部分内容被换为newval后,必须加此语句。因为newval不是s本身的内容,迭代器若遍历并与oldval比较会报错iterator incompatible
		}
		else
			++i;
	}
}
int main()
{
	string str("To drive straight thru is a foolish, tho courageous act.");
	Replace(str, "tho", "though");
	Replace(str, "thru", "through");
	cout << str << endl;
	system("pause");
}

方法三(下标+replace):

#include<iostream>
#include<string>
using namespace std;
void Replace(string& s, const string& oldval, const string& newval)
{
	for (decltype(s.size())i = 0; i != s.size(); ++i)
	{
		if (s.substr(i, oldval.size()) == oldval)
		{
			s.replace(i, oldval.size(), newval);
			i += oldval.size() - 1;
		}
	}
}
int main()
{
	string str("to drive straight thru is a foolish, tho courageous act.");
	Replace(str, "tho", "though");
	Replace(str, "thru", "through");
	cout << str << endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/weixin_44009743/article/details/89010376