來自https://www.cnblogs.com/jm-Xu/p/9318705.html
string(s小寫)是C++標准庫中的類,純C中沒有,使用時需要包含頭文件#include<string>
1 string的定義及初始化 2 string s1 = "hello"; //初始化字符串 3 string s2 ("world"); //另一種初始化 4 5 string s3; //初始化字符串,空字符串 6 7 string s4(5, 'a'); //s4由連續5個a組成,即s4="aaaaa"; 8 string s5(s1,2,3); //從s1的2位置的字符開始,連續3個字符賦值給s5,即s5="llo"; 9 string s6(s1, 1); //從s1的2位置的字符開始,將后續的所有字符賦值給s6,即s6="ello";
1 重載的運算符 2 此處列舉一下被重載的運算符,基本意思一目了然。其中注意“+”操作 3 s1 = s2; 4 s1 += s2; 5 s1 = s2 + s3; 6 s1 == s2; 7 s1 = "s" + s2; //正確 8 s1 = "s" + "s"; //錯誤,加號兩邊至少要有一個string類型的對象 9 s1 = "s" + s2 + "s" + "s"; //正確 10 11 “+”的兩邊要保證至少有一個string類型,所以5正確,6錯誤。由於在C/C++中,+的返回值還是原類型,所以第7行中,"s"+s2返回一個string類型,因此string+“s”也是正確的,
1 遍歷string(迭代器) 2 遍歷string中的元素時,我們可以使用類似C中的數組形式訪問,如s1[1](下標從0開始) 3 4 也可以使用STL特有的迭代器訪問: 5 string::iterator it; 6 for (it = s1.begin(); it != s1.end(); it++){ 7 cout << *it << endl; 8 } 9 10 cout << *(s1.begin()); //正確,即訪問s1[0] 11 cout << *(s1.end()); //錯誤,s1.end()指向了空 12 若想要從后向前遍歷string時,可以用到rbegin()和rend()函數。 13 (參考vector博文)
1 插入insert() 2 string s1 = "hello"; 3 s1.insert(1,"ins"); //從s1的1位置開始,插入"ins"字符串,即s1="hinsello"; 4 s1.insert(1, "ins", 2);//從s1的1位置開始,插入"ins"字符串的前2個字符,即s1="hinello"; 5 s1.insert(1, "ins", 1, 2);//從s1的1位置開始,插入"ins"字符串的從1位置開始的2個字符,即s1="hnsello"; 6 7 iterator insert(iterator it, char c);//在it處插入字符c,返回插入后迭代器的位置
1 刪除erase() 2 iterator erase(iterator first, iterator last);//刪除[first,last)之間的所有字符,返回刪除后迭代器的位置 3 iterator erase(iterator it);//刪除it指向的字符,返回刪除后迭代器的位置 4 string &erase(int pos = 0, int n = npos);//刪除pos開始的n個字符,返回修改后的字符串 5 6 7 查找 find() 8 cout << s.find("aa", 0) << endl; //返回的是子串位置。第二個參數是查找的起始位置,如果找不到,就返回string::npos 9 if (s.find("aa1", 0) == string::npos) 10 { 11 cout << "找不到該子串!" << endl; 12 }