為什么要寫STL淺談這個系列,因為最近我在準備藍橋杯,刷題的時候經常要用到STL,準備補一補,但一直沒有找到一個好的視頻和資料,最開始準備跟著c語言中文網學,但覺得太繁雜了,最后在b站(b站上計算機類的教學視頻挺多的)上找了一個視頻學的,這個系列相當于我的一個整理,
這個系列只是淺談,但刷題應該夠了,
今天講<string>,直接上代碼(本人文采有限,習慣代碼+注釋),
#include<iostream> #include<string> using namespace std; int main() { //輸入輸出 string str1; //cin>>str1; //無法輸入有空格的字串 //cout<<str1<<endl; getline(cin, str1); //輸入一行字串 cout << str1 << endl; //字串拼接 string str2 = "hello"; str2 += " world!"; cout << str2 << endl; //str2="hello wrold!" //字串洗掉指定元素 str2.erase(str2.begin() + 1); //洗掉元素'e' /*string.begin()頭迭代器,指向第一個元素 string.end()尾迭代器,指向最后一個元素的后一個位置*/ cout << str2 << endl; //str2="hllo wrold!" //字串截取 str2 = "hello wrold"; string str3 = str2.substr(1, 3); //第一個引數是起始下標,第二個引數是截取長度 cout << str3 << endl; //str3="ell" //for回圈 for (int i = 0; i < str2.length(); i++) //字串長度:str.length() cout << str2[i]; cout << endl; //迭代器回圈 for (string::iterator it = str2.begin(); it < str2.end(); it++) cout << *it; cout << endl; //auto指標 for (auto it = str2.begin(); it < str2.end(); it++) cout << *it; cout << endl; //foreach回圈 for (auto ch : str2) cout << ch; cout << endl; //字串插入 str2.insert(1, "ello"); //第一個引數是起始下標,第二個引數是插入字串 cout << str2 << endl; //str2="helloello wrold" //字串交換 str3 = "end!"; str2.swap(str3); cout << str2 << endl; //str2 = "end!" return 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/42995.html
標籤:C++
上一篇:std::bind介面與實作
