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遍历(C++11)
void test_string2() { string s1("hello"); s1 += " "; s1 += "world"; // 范围for c++11 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 h
string转换成整数类型
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) 则只会遇到换行才结束
