【C++学习笔记】基于范围的for语句

本文介绍了C++中基于范围的for循环的应用,包括处理字符串中的每个字符、改变字符串中的字符大小写以及仅处理字符串的一部分字符等操作。文章通过具体实例展示了如何使用这种循环进行高效的字符串操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++Primer P82-84

##基于范围的for语句

作用

#####1. 处理每一个字符
#####2. 改变字符串的每一个字符
#####3. 只处理一部分字符

######1. 处理每一个字符

#include <iostream>
#include <string>
#include <cctype>

using namespace std;
using std::string;

int main()
{
	string str("hEllo WorLD");
	int lownum=0;
	//通过使用auto关键字,让编译器来决定变量X的类型。这里的x类型是char
	for (auto x : str)
	{
		if (islower(x))
		{
			lownum++;
		}
	}
	cout << lownum << endl;

	return 0;
}

######2. 改变字符串的每一个字符

#include <iostream>
#include <string>
#include <cctype>

using namespace std;
using std::string;

int main()
{
	string str("hEllo WorLD!!!");
	
	for (auto &x : str)
	{
		x = toupper(x);
	}
	cout << str << endl;

	/*
	=要点=
	如果想改变string对象中字符的值,必须把循环变量定义成引用类型
	*/
	return 0;
}

######3. 只处理一部分字符——使用下标执行迭代

#include <iostream>
#include <string>
#include <cctype>
using namespace std;
using std::string;
//代码把第一个空格键前的字符全都转变为大写
int main()
{
	string str("hEllo WorLD!!!");
	
	for (decltype(str.size()) index = 0;
		index != str.size() && !isspace(str[index]);
		index++)
		str[index] = toupper(str[index]);

	cout << str << endl;
	return 0;
}

######4. 只处理一部分字符——使用下标执行随机访问

/*
编写一个程序,把0到15之间的十进制数转换成对应的十六进制形式,
只允许初始化一个字符串令其存放16个十六进制的‘数字’
*/
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
using std::string;
int main()
{
	string str("0123456789ABCDEF");
	string result;
	string::size_type n;//?????????
	while (cin >> n)
	{
	   result += str[n];
	}
		
	cout << result << endl;
	//两个string的相加结果是拼在一起。
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值