C++標(biāo)準(zhǔn)模板庫string類的介紹與使用講解
更新時間:2018年12月21日 14:11:02 作者:蝸牛201
今天小編就為大家分享一篇關(guān)于C++標(biāo)準(zhǔn)模板庫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 使用下標(biāo)
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);//返回從下標(biāo)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)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
C語言數(shù)據(jù)結(jié)構(gòu)之單鏈表存儲詳解
鏈表是一種物理存儲結(jié)構(gòu)上非連續(xù)、非順序的存儲結(jié)構(gòu),數(shù)據(jù)元素的邏輯順序是通過鏈表中的指針鏈接次序?qū)崿F(xiàn)的。本文將和大家一起聊聊C語言中單鏈表的存儲,感興趣的可以學(xué)習(xí)一下2022-07-07

