cplusplus,非官網,但布局比較美觀,支持到C++11
cppreference,官網,可支持到最新標準,但布局不太美觀
檔案一般結構布局為:介面函式宣告——>介面函式的功能、引數以及回傳值的說明——>使用樣例代碼
那讓我們正式進入string類的學習吧!
首先,在STL中的string類有9個建構式,此處以最常用的3個和大家一起來學習
- string類的無參建構式
- string類的有參建構式
- string類的拷貝建構式
string s1; //無參構造
string s2("come on"); //帶參的構造
string s3(s2) //拷貝構造
string s4="come on";
s1 = "happy";
//等價于帶引數的構造,string支持char型別字串的構造
運行結果
拓展小知識:
1.wchar_t 為寬位元組,2byte 其能夠更好的表示unicode等編碼,其對應STL中的wsting,而常見的為char對應的sting
2.ascll碼其實是早起針對英文的編碼,而后來為了顯示各個國家的語言文字,便引入了unicode,utf-8,uft-16,uft-32等編碼,
gbk即是專門針對中文的編碼方式,
接下來,讓我們通過一道簡單的練習再進一步理解一下吧!
原題鏈接
解題思路:
方法一,下標+[ ]遍歷并+計數排序思想
class Solution {
public:
int firstUniqChar(string s) {
int count[26]={0};
for(size_t i=0;i<s.size();++i)
{
count[s[i]-'a']++;
}
for(size_t i=0;i<s.size();++i)
{
if(count[s[i]-'a']==1)
return i;
}
return -1;
}
};
方法二,迭代器遍歷+計數排序思想
class Solution {
public:
int firstUniqChar(string s) {
int count[26]={0};
string::iterator it=s.begin();
while(it!=s.end())
{
count[*it-'a']++;
++it;
}
for(size_t i=0;i<s.size();++i)
{
if(count[s[i]-'a']==1)
return i;
}
return -1;
}
};
方法三,范圍for遍歷+計數排序思想
class Solution {
public:
int firstUniqChar(string s) {
int count[26]={0};
for(auto x: s)
{
count[x-'a']++;
}
for(size_t i=0;i<s.size();++i)
{
if(count[s[i]-'a']==1)
return i;
}
return -1;
}
};
總結一下,其實三種方法唯一的區別就是三種的遍歷方法不同,思路的中都是計數排序的思想,
想了解三種遍歷方式的詳細情況嗎?點擊這里吧!
string.erase()用法
- string.erase(pos,n)洗掉從pos開始的n個字符(pos是string型別的迭代器)
默認pos=0,n=nps=-1 - string.erase(pos)洗掉pos處的字符
- string.erase(first,last)洗掉從first到last中間的字符
string s1;
s1.erase(0,1);
s1.erase(); //為全部刪完
尾插
1.push_back(’ ')插入單個字符
2.append(" ")插入字串,也可進行拷貝構造
3.直接使用+=,可直接插入單個字符,也可以插入字串
string s1;
s1.push_back('i');
s1.append("world");
string s2;
s2.append(s1);
s1+="rh"; //其實底層呼叫的還是前兩個介面
s1+='l';
頭插或中間插入
string.insert()
注意不支持插入單個字符,但可以插入一個字符的字串
string s1;
s1.insert(0,"x"); //頭插
s1,insert(3,"yyyy"); //中間插
雖可以進行頭插和中間插,但盡量少用insert,因為底層實作的是陣列,頭插或者中間插入是需要挪動資料的,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/396192.html
標籤:其他
下一篇:git工具
