<string.h>
初始化string
string s1;
string s2(s1);
string s3("string");
string s4(10, 'c');
string的输入
stream is, os;
os << s;
is >> s;
getline(is, s); // 从is中读取一行给s,返回is
- getline()
getline()函数的参数是一个流is和一个string对象。
从is中读入内容,直到遇到换行符为止。(NOTE:换行符也被读进来了,但是string中不存换行符)
string长度
s.empty() 返回1(为空),0(不为空)
s.size() 返回s中字符的个数
string的遍历
// 范围for语句
// c若加上&,则可以修改s中的内容
for (auto &c L s)
cout << c << endl;
string的修改
substr()
string s2 = s.substr(pos, n);
// 返回pos开始,长度为n的string
assign(), insert(), erase()
- 所有顺序容器都支持迭代器版本的这三个函数
- 这里介绍下表版本的:
s.insert(pos, n, t); // 在pos之前,插入n个值为t的元素,这里t为字符型('c')
s.erase(pos, n); // 删除pos开始的n个元素
string 的搜索
s.find(args); // 返回args第一次出现的位置
s.find_first_of(args); // 返回args中任何一个字符第一次出现的位置
string的数值转换
to_string(val); // 一组重载函数,任意类型数值 -> string
stoi(s, p, b); // string -> int
stol(s, p, b); // string -> long
stof(s, p); // string -> float
stod(s, p); // string -> double
// p是size_t指针,返回参数,保存s中第一个非数值字符的下标,p默认为0
// b为要转换的基数,默认为10
<vector.h>
初始化vector
vector<T> v1;
vector<T> v2(v1);
vector<T> v3(n, val);
vector<T> v4 = {a, b, c};
vector添加、删除元素
v.push_back(t);
v.push_front(t);
v.insert(p, t);
v.insert(p, args); // 在p之前插入一个args
vector的长度
v.empty();
v.size(); // 返回v中元素的个数
c.capacity(); // 返回v的最大容量
<>