图片来源:《C++ Primer中文版(第5版)》
特殊函数
#include <cctype>
统计标点符号
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string s = "hello!";
int size=0;
for(auto c:s)
if(ispunct(c))
size++;
cout<<size;
return 0;
}
运行结果为1。for(auto c:s)是C++11新标准提供的一种语句:范围for语句。这种语句遍历给定序列的每个元素,并对序列中的每个值执行某种操作,等效于for(int i = 0; i < s.size(); i++)
。这是一种非常适合遍历List、Vector、数组、字符串的语句。
ispunct©函数功能:当c是标点符号时为真(即c不是控制字符、数字、字母、可打印空白中的一种)。
将字符串中的小写字母转换为大写
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string s = "hello!";
for(auto &c:s)
c = toupper(c);
cout<<s;
return 0;
}
输出结果为:HELLO!
当我们需要改变遍历的元素时,必须把循环变量定义成引用类型。所谓引用只是给定对象的一个别名,因此当我们去改变这个引用,就会改变其绑定的对象。
toupper(c)函数功能:如果c是小写字母,输出对应的大小字母;否则原样输出c。
将首字母转换为大写
#include <iostream>
#include <cctype>
using namespace std;
int main() {
string s = "hello!";
if(!s.empty())
s[0] = toupper(s[0]);
cout<<s;
return 0;
}
输出结果:Hello!
将第一个词转换为大写
string s = "hello word!";
for(int i=0; i!=s.size() && !isspace(s[i]);i++)
s[i] = toupper(s[i]);
cout<<s;
return 0;
输出结果:HELLO word!
isspace(c)函数:当c是空白时为真(即c是空格、横向制表符、纵向制表符、回车符、换行符、进纸符中的一种)