C++Primer第五版:练习3.6 3.7 3.8 3.9 3.10 3.11

练习3.6

int main()
{
    
    
	string s = "Hello world!";

	for (auto& c : s)
		c = 'X';
	cout << s << endl;
}

练习3.7

auto关键字类型为char,结果不变

练习3.8

int main()
{
    
    
	string s = "Hello world!";

	for (string::size_type i = 0; i != s.size(); ++i)
		s[i] = 'X';

	string::size_type i = 0;
	while (i != s.size())
		s[i++] = 'X';
}

我认为for循环更好,更加直观方便

练习3.9
不合法,string默认初始化是一个空串,下标超出范围

练习3.10

#include<iostream>
#include<cctype>
using namespace std;

int main()
{
    
    
	string s = "Hello world!";

	for (auto& c : s)
		if (ispunct(c))
			c = ' ';
	cout << s << endl;
}

练习3.11
合法,c的类型为char&
可以访问但不能改值

猜你喜欢

转载自blog.csdn.net/Xgggcalled/article/details/109009060
今日推荐