使用范围for语句处理string对象
语法形式:
for (declaration:expression)
statement
示例1:统计string对象里面标点符号的个数
int main()
{
string s = "Hello World!!!";
decltype(s.size()) punct = 0;
for (auto c : s)
if (ispunct(c))
punct++;
cout << punct << " punctuation characters in " << s << endl;
return 0;
}
如果想要改变对象中字符的值,必须把循环变量定义为引用类型。
示例2:把字符串改写为大写字母形式
int main()
{
string s = "Hello World!!!";
for (auto &c:s)
c=toupper(c);
cout<<s<<endl;
return 0;
}