C++ Primer 第5版--练习9.43 & 9.44

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

注意:以下代码用codeblocks编译无法通过,用visual studio2015编译可以通过。

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

void replace_char(string &s, const string &oldVal, const string &newVal)
{
	auto iter = s.begin();
        //循环判定条件中,s.end()一定要减去oldVal.size(),否则程序虽然能够编译成功,但运行时会出错,因为循环主体中的iter + oldVal.size()会越界。
	//循环判定需要使用"<=",而不使用"!=",否则s的最后一个字符会无法替换。
	while (iter <= s.end() - oldVal.size()) 
	{
		if (string(iter, iter + oldVal.size()) == oldVal)
		{
			iter = s.erase(iter, iter + oldVal.size());
			iter = s.insert(iter, newVal.cbegin(), newVal.cend());
			iter += newVal.size();
		}
		else
			++iter;
	}
}

int main()
{
	//以下字符串中的"thotho"是特意用来测试待替换string连在一起的情况的。
	string s("What do I discover thotho? It looks as tho it might clear up tho.");
	//string oldVal("tho"), newVal("though");
	cout << "原string:" << s << "\n替换后为:";
	replace_char(s, "tho", "though");
	cout << s << endl;

	//以下字符串用于测试函数能否正确地替换最后一个字符
	string ss("who I am?");
	cout << "原string:" << ss << "\n替换后为:";
	replace_char(ss, "?", "...");
	cout << ss << endl;

	return 0;
}

练习 9.44:重写上一题的函数,这次使用一个下标和replace。

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

void replace_char(string &s, string oldVal, string newVal)
{
    int i = 0;
    while (i != s.size())
        if (s.substr(i, oldVal.size()) == oldVal)
        {
            s.replace(i, oldVal.size(), newVal);
            i += newVal.size();
        }
        else
            ++i;
}

int main()
{
	//以下字符串中的"thotho"是特意用来测试待替换string连在一起的情况的。
	string s("What do I discover thotho? It looks as tho it might clear up tho.");
	//string oldVal("tho"), newVal("though");
	cout << "原string:" << s << "\n替换后为:";
	replace_char(s, "tho", "though");
	cout << s << endl;

	//以下字符串用于测试函数能否正确地替换最后一个字符
	string ss("who I am?");
	cout << "原string:" << ss << "\n替换后为:";
	replace_char(ss, "?", "...");
	cout << ss << endl;

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值