C++標準模板庫string類的介紹與使用講解
更新時間:2018年12月21日 14:11:02 作者:蝸牛201
今天小編就為大家分享一篇關(guān)于C++標準模板庫string類的介紹與使用講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
介紹
c++中字符串string對象屬于一個類,內(nèi)置了很多實用的成員函數(shù),操作簡單,方便更直觀。
命名空間為std,所屬頭文件<string> 注意:不是<string.h>。
跟進代碼會發(fā)現(xiàn)string其實只是basic_string模板類的一個typedef。
賦值
//方法1 string str1 = "woniu201"; //方法2 char* p = "woniu201"; string str2 = p;
遍歷
//方法1 使用下標 for (int i=0; i<str1.length(); i++) { printf("%c", str1[i]); } //方法2 使用迭代器 string::iterator it; for (it=str1.begin(); it!=str1.end(); it++) { printf("%c", *it); }
查找
string str5 = "woniu201"; int pos1 = str5.find("n", 0); //從位置0開始查找字符n在字符串str5中的位置 int pos2 = str5.find("niu", 0); //從位置0開始查找字符串niu在字符串str5中的位置 int pos3 = str5.find("niu", 0, 2);//從位置0開始查找字符串niu前兩個字符組成的字符串在str5中的位置
截取
string str3 = "woniu201"; string str4 = str3.substr(0,5);//返回從下標0開始的5個字符組成的字符串
其他
//字符串連接 string str6 = "woniu201"; string str7 = "hailuo201"; string str8 = str6 + str7; //判斷是否相等 bool bRet1 = (str6 == str7); //相等為true,否則為false //判斷字符串是否為空 bool bRet2 = str6.empty(); //字符串插入 string str9 = str6.insert(0, str7); //字符串str6的0位置插入字符串str7 //字符串交換 str6.swap(str7); //判斷是否包含 string::size_type idx = str6.find("woniu"); if(idx == string::npos) { cout << "not found" << endl; }
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
在c和c++中實現(xiàn)函數(shù)回調(diào)
如何在c和c++中實現(xiàn)函數(shù)回調(diào)呢?現(xiàn)在小編就和大家分享一下在c/c++中實現(xiàn)函數(shù)回調(diào)的示例代碼,需要的朋友可以參考下2013-07-07M1 Macbook vscode C++ debug調(diào)試實現(xiàn)
本文主要介紹了M1 Macbook vscode C++ debug調(diào)試,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08