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;
}