- 初始化用法
#include <iostream> #include "string" using namespace std; void main() { string m1 = "陳培昌"; string m2("付高峰"); string m3 = m2; cout<<"m1:"<<m1<< endl; cout<< "m2:" << m2 << endl; cout<< "m3:" << m3 << endl; }
- 三種遍歷方式
void main() { string chroums = "Deep love is a burning fire Stay"; //方法一:數組遍歷 int i; for (i=0;i<chroums.length();i++) { cout << chroums[i]; } cout<<endl << "==============================" << endl; //方法二:迭代器 for (string::iterator it = chroums.begin(); it != chroums.end(); it++) { cout << *it; } string myequal(30, '*');//一次性生成30個* cout<<endl<<myequal << endl; //方法三:at() for (i = 0; i < chroums.length(); i++) { cout << chroums.at(i); } string anotherequal(40, '$'); cout << endl << anotherequal << endl; }
輸出結果:
- 選擇at()方法遍歷的好處----可以捕捉異常,注意示例中,故意越界訪問
void main() { string chroums = "Deep love is a burning fire Stay"; string myequal(30, '*');//一次性生成30個* cout << endl << myequal << endl; //方法三:at() int i = 0; try { for (i = 0; i < chroums.length() + 3; i++) { cout << chroums.at(i); } } catch (...) { cout << endl; cout << "crisis happend" << endl; } system("pause"); }
輸出結果:
- 而選用其他方式遍歷,盡管采取措施捕捉異常,仍舊無法制止錯誤
#include <iostream> #include "string" using namespace std; void main() { string chroums = "Deep love is a burning fire Stay"; //方法二:迭代器 try { for (string::iterator it = chroums.begin(); it != chroums.end()+3; it++) { cout << *it; } } catch (...) { cout << "crisis happend" << endl; } string anotherequal(40, '$'); cout << endl << anotherequal << endl; }
輸出結果:
- 查找目標字符串位置
void main() { string mywords = "Brother Louie, Louie, Louie"; size_t step3 = mywords.find("Louie",0);//size_t是C語言int類型的一種引用 cout <<"在字符串索引處"<< step3<<"找到目標字符串" << endl; }
輸出結果:
改進:持續查找(偏移量不等於字符串的末尾)
void main() { string mywords = "Brother Louie, Louie, Louie"; size_t step3 = mywords.find("Louie",0);//size_t是偏移量,在C語言中是int類型的引用 while (step3!=string::npos) { cout << "在字符串索引處" << step3 << "找到目標字符串" << endl; step3 = step3 + 1; step3 = mywords.find("Louie", step3); } }
輸出結果:
- 替換
void main() { string mywords = "徐曉冬卷了一只烤鴨餅,兀自咀嚼了起來。而陳培昌盛了一勺湯,品着陷入了沉思"; mywords.replace(0,6,"付高峰"); cout << mywords <<endl; }
輸出結果:
- 特別位置上的替換
void main() { string mywords = "付高峰卷了一只烤鴨餅,兀自咀嚼了起來。而陳培昌盛了一勺湯,品着陷入了沉思"; mywords.replace(0,6,"徐曉冬"); size_t cpc = mywords.find("陳培昌",0); mywords.replace(cpc,6,"吳子龍"); cout << mywords <<endl; }
輸出結果:
- 截斷
void main() { string mywords = "Brother Louie, Louie, Louie"; //size_t t = mywords.find("烤羊腿",0); string::iterator it = find(mywords.begin(),mywords.end(),'L'); if (it!= mywords.end()) { mywords.erase(it); } cout << mywords << endl; //截斷字符串erase() }
輸出: