大寫字母換成對應的小寫字母,小寫字母換成對應的大寫字母。爲避免領導難堪,還需要將其中的“government_official” (不論大小寫)替換爲“temporary_worker”(全部小寫)

1. 題意描述:

提示用戶從鍵盤輸入一句話(可能換行及包含空格,以EOF標記作爲結束,即用戶輸入Ctrl+Z作爲輸入結束),將其中的大寫字母換成對應的小寫字母,小寫字母換成對應的大寫字母。爲避免領導難堪,還需要將其中的“government_official”

(不論大小寫)替換爲“temporary_worker”(全部小寫)。最後將替換前後的兩句話分別顯示在屏幕上。 要求:

l 使用string對象和應用于string對象的函數;

l 在輸出替換前後的文字時需去除原輸入語句中多餘的空白符(即多于一個的連續的空白符)。



#include"iostream"
#include"string"
#include"cctype"

using namespace std;

void to(string& a)
{
	for(string::size_type i=0;i<a.size();i++)
	{
		if(isalpha(a[i]))
		{
			if(islower(a[i])) a[i]=toupper(a[i]);
			else if(isupper(a[i])) a[i]=tolower(a[i]);
		}
	}
}



//删除多余空格
void space(string& a)
{
	string::size_type i;
	while((i=a.find("  "))!=a.npos)
	{
		a.erase(i+1,1);
	}
}

int main()
{

	string a,t;
	string& b=a;
	string::size_type i;
	const string q="government_official";
	const string r="GOVERNMENT_OFFICIAL";
	const string h="TEMPORARY_WORKER";


	//输入
	cout<<"请输入一句话:"<<endl;
	getline(cin,a,'');
	cout<<"原话为:"<<a<<endl;

	//space(b);

	t=a;

	while((i=t.find(q))!=t.npos)
	{
		t.erase(i,q.size());

		a.erase(i,q.size());

		a.insert(i,h);

		t=a;
	}

	while((i=t.find(r))!=t.npos)
	{
		t.erase(i,r.size());

		a.erase(i,r.size());

		a.insert(i,h);

		t=a;
	}

	space(b);
	//大小写转换
	to(b);

	cout<<"修改后为:"<<a<<endl;

	return 0;
}


原文地址:https://www.cnblogs.com/cnsec/p/13286589.html