构造函数
关于构造函数就不过多介绍了,分析研究下下面的程序就可以理解
#include<iostream>
#include<string>
using namespace std;
int main() {
string one("lottery winner!");
cout << one << endl;
string two(20,'$');
cout << two << endl;
string three(one);
cout << three << endl;
one += "oops!";
cout << one << endl;
two = "sorry! that was ";
three[0] = 'p';
string four;
four = two + three;
cout << four << endl;
char alls[] = "all's well that ends well";
string five(alls,20);
cout << five << "!\n";
string six(alls+6,alls+10);
cout << six << ", ";
string seven(&five[6],&five[10]);
cout << seven << "...\n";
string eight(four,7,16);
cout << eight << " in motion!" << endl;
return 0;
}
程序输出:
把程序单步调试一下观察下string变量的值就理解了。
C++11的新增了构造函数移动构造以及列表初始化构造,前者和移动语义的理念一样,将右值权限转移给新的变量,避免了拷贝,优化性能。第二个列表初始化构造就是
string str{'f','e','e'};
这个可能用处不大。
string类输入(获取用户输入写入到string里面去)
string类有三种输入方式:
1.cin>> //从输入中读取一个字符 ,处理分隔符可加ignore()
2.cin.getline() //从输入中读取一行,舍弃分割符
3.cin.get() //从输入中读取单个字符或者字符串,不会丢弃分隔符(需手动处理)
都会自动在末尾添加/0(空字符)
迭代器
迭代器相当于指针
begin和end:begin指向string的第一个字符,end指向结尾的/0
rbegin和rend:rbegin指向string的最后一个有效字符,rend指向string头字符的前一个位置
cbegin和cend:适配const类型的string,和begin差不多
他们++就是向下一个位置走,--就是向上一个位置走
关于容量的函数
length stl出现之前就有,返回字符串长度
size 适配stl出现的函数,也是返回字符串长度,但实际更多,他包含了/0
capacity 返回string开辟的空间大小
empty 字符串是否为空,是返回true,否返回false
clear 清空有效字符
reserve 扩充string空间,为后续创建开辟新的空间
resize 将有效字符个数改为n个,多余的用参数c填充