美文网首页
c++ primer 阅读 day6

c++ primer 阅读 day6

作者: HenryTien | 来源:发表于2017-12-25 21:28 被阅读3次

3.2.3 处理string对象中的字符

遍历string中的每个字符

#include<iostream>

int main()
{
    /*
    std::string str("some string");
    //每行输出 str中的一个字符
    for(auto c : str)
        std::cout<<c<<std::endl;
    */

    /*
    std::string s("Hello World!!!");
    // punct_cnt 的类型和s.size的返回类型一样
    decltype(s.size()) punct_cnt = 0;
    for(auto c:s)
        if(ispunct(c))
            ++punct_cnt;
        std::cout<<punct_cnt
            <<" punctuation characters in "<< s <<std::endl;

      */

      std::string s("some string");
      for(decltype(s.size()) index = 0;
        index != s.size() && !isspace(s[index]);++index)
            s[index] = toupper(s[index]);
        std::cout<<s<<std::endl;

      std::string s1("hello world!!!");
      //转换为大写形式
      for(auto &c:s1)      //对于s中的每个字符(注意:c是引用)
        c = toupper(c);     //c是一个引用,因此赋值语句将改变s中字符的值
      std::cout<<s1<<std::endl;
    return 0;
}

note:
string 对象的下标必须大于等于0而小于s.size()。
使用超出下标的将引发不可预知的结果。

相关文章

网友评论

      本文标题:c++ primer 阅读 day6

      本文链接:https://www.haomeiwen.com/subject/uxdtgxtx.html