string对象中字符的处理
注意cctype头文件中的函数:
1. 处理每个字符:
范围for语句:
for(declaration : expression)
statement
1.1 例如:输出某个句子中的标点符号的个数
string s(“ll is a girl, who is my favorite girl!!!”);
decltype(s.size())punct_cnt=0; //用来统计s中标点符号的个数
for(auto c:s) //c与s中的每个字符对应
if(ispunct(c)) //如果c是标点符号,ispunct函数在cctype头文件中有定义
++punct_cnt; //统计值加1
cout<<punct_cnt<<endl;
1.2 将某个字符串全部修改为大写字母
string s(“ll is a girl, who is my favorite girl!!!”);
for(auto &c:s) //c与s中的每个字符对应,并且c是该字符的引用
c=toupper(c);//c是引用,将会改变s中的值,toupper函数是ccype头文件的函数
cout<<s<<endl;
2. 处理部分字符
下标运算符:[ ]
下标运算符的输入参数是string::size_type类型的值,参数表示访问的字符的位置,是无符号数,从0开始取值;返回该位置对应字符的引用。
2.1 使用下标将字符串第一个单词改为大写
string s(“some thing”);
for(decltype(s.size())index = 0;index != s.size()&&!isspace(s[index]);++index)
s[index] = toupper(s[index]); //函数isspace是cctype头文件中的函数
输出为: SOME thing