【C++ Primer第五版】——第三章 编程题

本篇博客涵盖C++ Primer第五版第三章的编程练习,包括读取输入、字符串操作、数组与vector的使用、字符处理以及迭代器的应用等,旨在提升C++编程技能。
摘要由CSDN通过智能技术生成

3.2:编写一段程序从标准输入中一次读入一整行,然后修改程序使其一次读入一个词。

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
	std::string line;
	//一次读入一整行
	//while (getline(std::cin,line))
		//std::cout << line << std::endl;
	//一次只读入一个词
	while (std::cin >> line)
		std::cout << line << std::endl;
	system("pause");
	return 0;
}

3.4:编写一段程序读入两个字符串,比较其是否相等并输出结果。如果不相等,输出较大的那个字符串。改写上述程序,比较输入的两个字符串是否等长,如果不等长,输出长度较大的那个字符串。

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
	std::string s1, s2;
	std::cin >> s1 >> s2;

	//字符串大小比较
	/*if (s1 >= s2)
		std::cout << s1 << std::endl;
	else
		std::cout << s2 << std::endl;*/

	//字符串长度比较
	if (s1.size() != s2.size()){
		if (s1.size() > s2.size())
			std::cout << s1 << std::endl;
		else
			std::cout << s2 << std::endl;
	}

	system("pause");
	return 0;
}

3.5:编写一段程序从标准输入中读入多个字符串并将它们连接在一起,输出连接成的大字符串。然后修改上述程序,用空格把输入的多个字符串分隔开来。

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
	std::string s1, s2;

	while (std::cin >> s1){
		//字符串直接相加
		//s2 = s2 + s1;

		//字符串间用空格连接
		if (s2.size() == 0)
			s2 = s2 + s1;
		else
			s2 = s2 + " " + s1;
	}
	std::cout << s2 << std::endl;

	system("pause");
	return 0;
}

3.6:编写一段程序,使用范围for语句将字符串内的所有字符用X代替。

方法一:

c是一个引用,通过引用来改变它绑定的对象的字符。

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
	std::string str("some string!!!");
	for (auto &c:str){
		c = 'X';
	}
	std::cout << str << std::endl;

	system("pause");
	return 0;
}

方法二:

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
	std::string str("some string!!!");
	for (decltype(str.size()) i = 0; i < str.size(); i++){
		str[i] = 'X';
	}
	std::cout << str << std::endl;

	system("pause");
	return 0;
}

3.10:编写一段程序,读入一个包含标点符号的字符串,将标点符号去除后输出字符串剩余的部分。

ispunct(c):当c是标点符号时为真(即c不是控制字符、数字、字母、可打印空白中的一种)

同理,两种方法。

方法一:(此时C不为引用,因为创建了新的字符串ans保存去掉标点符号后的字符,原来的str不用发生改变)

#include <iostream>
#include <string>

int main(int argc, char* argv[])
{
	std::string str("some .string!!!");
	std::string ans;
	for (auto c:str){
		if (!ispunct(c))
			ans += c;
	}
	std::cout << ans << std::endl;

	system("pause");
	return 0;
}

方法二:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值