信息学奥赛一本通 2046:【例5.15】替换字母

【题目链接】

ybt 2046:【例5.15】替换字母

【题目考点】

1. 字符数组
2. string类
3. 读入带空格的字符串

由于NOIP官方开始使用C++14编译器,C语言中用于读取带空格字符串的gets()函数已经不可以再用了。作为替代,有以下方法。

  • cin.getline()函数。
    函数格式:
    cin.getline(字符数组名, 最大读入字符数)
    作用:读入一行带空格的字符串
    由于最大读入字符数中包含了’\0’,因此真正允许读入的字符数会比这个数字少1
    一般将这个参数填为数组的长度即可。
    例: cin.getline(s, 100); 最多能读入99个字符保存到字符数组s

  • 如果使用string类,可以使用getline()函数读入带空格的字符串
    getline(cin, string类对象)

【题解代码】

解法1:遍历的同时修改字符数组,最后输出字符数组
  • 使用字符数组
#include
using namespace std;
int main()
{
	char s[205], a, b;
	cin.getline(s, 205);//读入带空格的字符串,最多可以读入204个字符
    cin >> a >> b;
	int len = strlen(s);
	for(int i = 0; i < len; ++i)
	{
	    if(s[i] == a)
	       s[i] = b;
    }
	cout << s;
	return 0;
}
  • 使用string类:
#include
using namespace std;
int main()
{
    string s;
	char a, b;
	getline(cin, s);
    cin >> a >> b;
	for(int i = 0; i < s.length(); ++i)
	{
	    if(s[i] == a)
	       s[i] = b;
    }
	cout << s;
	return 0;
}
解法2:遍历字符数组,如果遇到需要替换的字符,输出替换后的字符
  • 使用字符数组
#include
using namespace std;
int main()
{
	char s[205], c1, c2;
	cin.getline(s, 205);
	cin >> c1 >> c2;
	int len = strlen(s);
	for(int i = 0; i < len; i++)
	{
		if(s[i] == c1)
			cout << c2;
		else
			cout << s[i];
	}
	cout << endl;
	return 0;
}
  • 使用string类
#include
using namespace std;
int main()
{
	char c1,c2;
	string s;
	getline(cin, s);
	cin >> c1 >> c2;
	for(int i = 0;i < s.size();i++)
	{
		if(s[i] == c1)
			cout << c2;
		else
			cout << s[i];
	}
	cout << endl;
	return 0;
}

你可能感兴趣的:(信息学奥赛一本通题解,c++)