码迷,mamicode.com
首页 > 编程语言 > 详细

[C++] 使用基于范围的for循环操作string

时间:2015-06-04 09:57:27      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:c++   c++11   

C++11提供范围for语句,这个语句遍历给定的序列中的每个元素并对序列中的每个元素执行某种操作:

for (declaration : expression)
    statement
  • 输出string中的每个字符:
    string str("some string");

    for (auto c : str)
    {
        cout << c << endl;
    }
在for循环中使用auto声明变量c,由编译器决定其类型,每次循环,将str中的下一个字符拷贝到c中。
  • 使用ispunct函数来统计string中标点符号的个数
    string s("Hello World!!!");
    decltype(s.size()) punct_cnt = 0;

    for (auto c : s)
    {
        if (ispunct(c))
            ++punct_cnt;
    }

    cout << punct_cnt << " punctuation characters in " << s << endl;
  • 使用范围for语句改变字符串的字符
    for (auto &c : s)
    {
        c = toupper(c);
    }

    cout << s << endl;
c是string s中字符的引用,使用toupper将string中字符改成大写字符。

[C++] 使用基于范围的for循环操作string

标签:c++   c++11   

原文地址:http://blog.csdn.net/yamingwu/article/details/46351845

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!