C++ STL学习之string(一) 默认成员函数之构造函数void test_string1() { string s1; // 构造函数 string s2(hello); // 带参构造 string s3(hello, 2); // 只拷贝前两个字符 string s4(s2); // 拷贝构造 string s5(s2, 1, 2); // 从第1个字符开始拷贝两个字符 string s6 s2; // 拷贝构造在赋值过程中调用了拷贝构造s6 在定义时用 s2 初始化调用拷贝构造 string s7; s7 s2; // s7 先定义默认构造再赋值调用的是拷贝赋值运算符 operator cout s1 endl; cout s2 endl; cout s3 endl; cout s4 endl; cout s5 endl; }输出string的遍历方法1、for循环遍历void test_string2() { string s1(hello); s1 ; s1 world; for (size_t i 0; i s1.size(); i) { cout s1[i] ; } cout endl; }2、迭代器遍历void test_string2() { string s1(hello); s1 ; s1 world; // 迭代器 string::iterator it s1.begin(); while (it ! s1.end()) { cout *it ; it; } cout endl; }3、范围for遍历C11void test_string2() { string s1(hello); s1 ; s1 world; // 范围for c11 for (auto ch : s1) { cout ch ; } cout endl; }4、反向迭代器反向遍历void test_string3() { string s1(hello world); string::reverse_iterator rit s1.rbegin(); while (rit ! s1.rend()) { cout *rit ; rit; } cout endl; }输出结果为d l r o w o l l e hstring转换成整数类型int string2num(const string nums) { int val 0; string::const_iterator vit nums.begin(); while (vit ! nums.end()) { val * 10; val (*vit - 0); vit; } return val; }上述代码中使用了const迭代器只能读不能写*vit的值不能再改变string的插入删除void test_string4() { string s1; s1.push_back(x); // 尾插在尾部插入一个字符输出x s1.append(11111); // 尾部插入字符串输出x11111 s1 yyy; // 尾部插入字符串输出x11111yyy string s; s 1; s 3456; cout s endl; // 输出13456 s.insert(s.begin(), 0); // 头插在1之前插入0 cout s endl; // 输出013456 s.insert(2, 2); // 在2的位置插入2 cout s endl; // 输出0123456 s.erase(2, 10); // 从第2个位置开始删除 cout s endl; // 输出01 }string的查找find()函数用法查找文件后缀名void test_string5() { string s1(string.cpp); string s2(string.c); string s3(string.txt); size_t pos1 s1.find(.); if (pos1 ! string::npos) { cout s1.substr(pos1) endl; } size_t pos2 s2.find(.); if (pos2 ! string::npos) { cout s2.substr(pos2) endl; } size_t pos3 s3.find(.); if (pos3 ! string::npos) { cout s3.substr(pos3) endl; } }string中getline()的用法string s;cin s; 遇到空格或者换行就回结束而getline(cing, s) 则只会遇到换行才结束