首页 > 编程语言 > 详细

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

时间:2015-06-04 09:56:11      阅读:365      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!