• 1 字符串的构造

一般会使用到的构造分为拷贝构造和直接构造

string str1="hello world";//拷贝构造
string str2(10,'c');//直接构造
string str3("hello world");//直接构造

输出得到

hello world
cccccccccc
hello world
  • 2 获取一行

cin在读取一行字符串的时候,当它遇到空格时就会结束,因此C++提供了getline来读取一行,它只有读到回车的时候才会结束。getline有两个参数,第一个参数表示从哪里读,第二个参数表示读到哪里

//输入 get a girlfriend
string str;
getline(cin,str);
cout<<str;
//输出 get a girlfriend
  • 3 常用方法

str.size()返回字符串的长度,返回值类型为size_t,也就是一个无符号数。

关于更多的使用建议参考cplusplus.

  • 情形四 一个小demo

现有字符串helloworld,让它转换成HELLOWPORLD

string str="helloworld";
//for(size_t i=0;i<str.size;i++)
for(char& s : str){
    s=toupper(s);
 }
    cout<<str;

上述提供了两种遍历字符串的方式,可以注意到在第一个for中,将i定义成了size_t类型,而不是int,这是因为符号数与无符号数之间的转换可能会有bug。在第二种遍历中由于要改变str的值,因此采用引用的方式去定义,回顾之前所讲的引用,s每次去作为str中一个字符的绑定,对s的改变就会同步到str