C C 字串string操作的全面總結

2021-10-25 06:20:07 字數 2032 閱讀 2315

字串操作看似簡單,其實非常重要,不注意的話,經常出現**執行結果和自己想要的不一致,甚至崩潰。總結一下構建string物件方法、修改string物件的方法、string型別的操作函式、string型別的查詢、string物件的比較。

首先,為了在我們的程式中使用string型別,我們必須包含標頭檔案 。如下:

#include

1.構建string物件方法

宣告乙個字串變數很簡單:

string str;

這樣我們就宣告了乙個字串變數,但既然是乙個類,就有建構函式和析構函式。上面的宣告沒有傳入引數,所以就直接使用了string的預設的建構函式,這個函式所作的就是把str初始化為乙個空字串。string類的建構函式和析構函式如下:

string s; //生成乙個空字串s

string s(s2); //拷貝建構函式 生成s2的複製品

string s(「value」); //用字串value初始化s

string s(n,『c』); //生成乙個字串,包含n個c字元

string s(b,e); //以區間b,e內的字元作為字串s的初值

string s(cp,n); //取字元陣列,前n個字元作初值

string s(s2,pos2); //將字串s2"始於位置pos2"部分當作字串的初值

string s(s2,pos1,len); //將字串s2內"始於pos1且長度最多len"的部分作為字串的初值

s.~string() //銷毀所有字元,釋放記憶體

下面是**例項

#include #include using namespace std;

int main()

string 型別特有的版本

string以陣列的形式儲存,可以用陣列的下標進行修改操作:

s.insert(pos,n,c); //在下標 pos 的元素之前插入 n 個字元 c

s.insert(pos,s2); //在下標 pos 的元素之前插入 string 物件 s2

s.insert(pos,s2,pos2,len); //在下標為 pos 的元素之前插入 s2 中從下標 pos2 開始的 len 個字元

s.insert(pos,cp,len); //在下標為 pos 打元素之前插入 cp 所指向陣列的前len 個字元

s.insert(pos,cp); //在下標為 pos 的元素之前插入 cp 所指向的以空字元結束的字串副本

s.assign(s2); //用 s2 的副本替換 s

s.assign(s2,pos2,len); //用 s2 中從下標 pos2 開始的 len 個字元替換 s

s.assign(cp,len); //用 cp 所指向陣列的前 len 個字元副本替換 s

s.assign(cp); //用 cp 所指向的以空字元結束的字串替換 s

s.erase(pos,len); //刪除從下標 pos 開始的 len 個字元

下面是**例項

#include #include using namespace std;

int main()

4、string型別的查詢

s.find( args); //在 s 中查詢 args 的第一次出現

s.rfind( args) // 在 s 中查詢 args 的最後一次出現

s.find_first_of( args) //在 s 中查詢 args 的任意字元的第一次出現

s.find_last_of( args) //在 s 中查詢 args 的任意字元的最後一次出現

s.find_first_not_of( args) //在 s 中查詢第乙個不屬於 args 的字元

s.find_last_not_of( args) //在 s 中查詢最後乙個不屬於 args 的字元

#include #include using namespace std;

int main()

C C 字串string操作(全)

include int i 123 string a to string i atoi使用 string a 123 a.c str 把 a 轉化為const char 型別 int b atoi a.c str b 123 stoi使用 string a 123 int b stoi a b 12...

C C 字串string操作的全面總結

字串操作看似簡單,其實非常重要,不注意的話,經常出現 執行結果和自己想要的不一致,甚至崩潰。總結一下構建string物件方法 修改string物件的方法 string型別的操作函式 string型別的查詢 string物件的比較。首先,為了在我們的程式中使用string型別,我們必須包含標頭檔案 如...

String字串操作

char chars string s new string chars int len s.length 字串長度 system.out.println chars ab system.out.println s abc system.out.println len 3 char ch zhang...