1. 程式人生 > 其它 >C++ String的進階操作II

C++ String的進階操作II

技術標籤:寒假自主學習字串

前邊說的都是string類的建構函式
下面這些是用於string操作的庫函式

substr()//主要功能是複製子字串,要求從指定位置開始,並具有指定的長度。
append() //方法在被選元素的結尾(仍然在內部)插入指定內容。提示:如需在被選元素的開頭插入內容,請使用prepend()方法。
replace()//該函式返回一個字串,其中指定的字串已經被替換為另一字串,並且替換的次數也可以指定。

程式碼例項:

#include <iostream>
#include <string>

using namespace std;
//20200425 測試字串操作  公眾號:C與C語言plus
int main() { string s("Hello world"); string s2 = s.substr(6,5); //從第6個開始取5個 cout << s2 << endl ; //s2為world s2 = s.substr(6); //從第6個開始取複製所有的 cout << s2 << endl ; //s2為world s2 = s.substr(6); //s2複製s,相當於s2=s cout << s2 << endl ;
//s2為Hello world s = "C++ Primer"; s.append(" 3rd Ed"); //再s最後新增3rd Ed cout << s<< endl ; //s為C++ Primer 3rd Ed s = "C++ Primer"; s.insert(s.size()," 3rd Ed"); //最後插入 cout << s<< endl ; //s為C++ Primer 3rd Ed s.replace(11,3,
"4th"); //下標11開始3個替換4th cout << s<< endl ; //s為C++ Primer 4th Ed s.replace(11,3,"Fourth"); //下標11開始3個替換Fourth cout << s<< endl ; //s為C++ Primer Fourth Ed s = "C++ Primer 3rd Ed"; //replace相當於先刪除後插入 s.erase (11,3); //刪除3rd s.insert(11,"Fourth"); //插入Fourth cout << s<< endl ; //s為C++ Primer Fourth Ed return 0; }