C string類常用函式

2021-09-23 01:33:47 字數 2349 閱讀 7845

string類的建構函式:

string(const char *s);   //用c字串s初始化

string(int n,char c);   //用n個字元c初始化

此外,string類還支援預設建構函式和複製建構函式,如string s1;string s2="hello";都是正確的寫法。當構造的string太長而無法表達時會丟擲length_error異常

string類的字元操作:

const char &operator(int n)const;

const char &at(int n)const;

char &operator(int n);

char &at(int n);

operator和at()均返回當前字串中第n個字元的位置,但at函式提供範圍檢查,當越界時會丟擲out_of_range異常,下標運算子不提供檢查訪問。

const char *data()const;//返回乙個非null終止的c字元陣列

const char *c_str()const;//返回乙個以null終止的c字串

string的特性描述:

int capacity()const;   //返回當前容量(即string中不必增加記憶體即可存放的元素個數)

int max_size()const;   //返回string物件中可存放的最大字串的長度

int size()const;     //返回當前字串的大小

int length()const;     //返回當前字串的長度

bool empty()const;     //當前字串是否為空

void resize(int len,char c);//把字串當前大小置為len,並用字元c填充不足的部分

string類的輸入輸出操作:

string類過載運算子operator>>用於輸入,同樣過載運算子operator《用於輸出操作。

函式getline(istream &in,string &s);用於從輸入流in中讀取字串到s中,以換行符'\n'分開。

string的賦值:

string &operator=(const string &s);//把字串s賦給當前字串

string &assign(const char *s);//用c型別字串s賦值

string &assign(const char *s,int n);//用c字串s開始的n個字元賦值

string &assign(const string &s);//把字串s賦給當前字串

string &assign(int n,char c);//用n個字元c賦值給當前字串

string &assign(const string &s,int start,int n);//把字串s中從start開始的n個字元賦給當前字串

string &assign(const_iterator first,const_itertor last);//把first和last迭代器之間的部分賦給字串

string的連線:

string &operator+=(const string &s);//把字串s連線到當前字串的結尾

string的比較:

bool operator==(const string &s1,const string &s2)const;//比較兩個字串是否相等

運算子">","<",">=","<=","!="均被過載用於字串的比較;

int compare(const string &s) const;//比較當前字串和s的大小

int compare(int pos, int n,const string &s)const;//比較當前字串從pos開始的n個字元組成的字串與s的大小

int compare(int pos, int n,const string &s,int pos2,int n2)const;//比較當前字串從pos開始的n個字元組成的字串與s中pos2開始的n2個字元組成的字串的大小

int compare(const char *s) const;

int compare(int pos, int n,const char *s) const;

int compare(int pos, int n,const char *s, int pos2) const;

compare函式在》時返回1,《時返回-1,==時返回0 

string的字串:

string substr(int pos = 0,int n = npos) const;//返回pos開始的n個字元組成的字串 

string的交換:

void swap(string &s2);   //交換當前字串與s2的值

C string類 vector類 常用函式

vectora 宣告乙個int型向量a vectora 10 宣告乙個初始大小為10的向量 vectora 10,1 宣告乙個初始大小為10且初始值都為1的向量 vectorb a 宣告並用向量a初始化向量b vectorb a.begin a.begin 3 將a向量中從第0個到第2個 共3個 作...

C string類的常用函式

1 string 類的物件可以直接賦值 string operator const string s 2 string operator const string s 3 還可以直接用運算子 直接比較字串。4 string.swap string s2 交換當前字串與s2的值。5 string.fi...

CString類常用的幾個函式

cstring strtemp 去掉最後乙個字元 strtemp strtemp.left strtemp.getlength 1 或strtemp.setat strtemp.getlength 1,0 字元 字串替換函式 刪除strtemp中某個字元或字串 strtemp.replace str...