导航

C++学习笔记(7)标准库string类

Posted on 2015-07-01 16:43  Charles__Wang  阅读(109)  评论(0)    收藏  举报

一、初始化string对象:

      直接初始化:string a("value");

      拷贝初始化:string a = "value";

二、读写string对象

      注:cin会忽略头尾空白处,保留空白符需要使用getline;

      empty函数判断是否为空,size函数计算字符串长度。

      不能把多个字面值直接相加赋值给string对象,字符串字面值不是string对象

三、范围for语句的使用

      

    string str("some,string!!!");
    for(auto c : str)
    {
        cout<< c << endl;//逐行打印每个字符
    }
    decltype(str.size()) punct_cnt = 0;
    for(auto i : str)
    {
        if (ispunct(i))
        {
            ++punct_cnt;
        }

    }
    cout<< punct_cnt<<endl;    //输出标点符号数4
  

  for(auto &b : str)
  {
    b = toupper(b); //小写变大写
  }
  cout<<str<<endl;

 四、使用下标运算符改变string对象部分值

    

 1 if (!str.empty())
 2 {
 3 str[0]= toupper(str[0]);//首字母大写
 4 }
 5 cout<<str<<endl;
 6 
 7 
 8 for(decltype(str.size()) index = 0; index != str.size()&&!isspace(str[index]);++index)
 9 {
10     str[index] = toupper(str[index]);//第一个字母大写
11 }
12 cout<<str<<endl;