C++中關于string類的一些API總結
參考資料:http://www.rzrgm.cn/X-Do-Better/p/8628492.html;
https://blog.csdn.net/iot_change/article/details/8496977
一、前言
對于C++中的string類,需要使用的話,需要包含頭文件<string>。string類在C++中屬于一個模板類,位于命名空間namespace中,使用的時候需要加上下一語句。
1 using namespace std;
二、自身特性方面的API
1、int capacity()
功能描述:返回當前容量【即string中在不需要增加內存的情況下還可存放的元素個數(shù)】。
2、int max_size()
功能描述:返回string對象中可存放的最大字符串的長度。
3、int size()
功能描述:返回當前字符串的大小
4、int length()
功能描述:返回當前字符串的長度
5、bool empty()
功能描述:判斷當前字符串是否為空
6、void resize(int len, char c)
功能描述:把字符串當前大小設置為len,多去少補,字符c填充不足的部分
三、關于查找方面的API
1、size_type find ( const basic_string &str, size_type index )
功能介紹:返回str在字符串中第一次出現(xiàn)的位置,從index開始查找,如果查找失敗,則返回string::npos。
類似的API還有以下幾個。
size_type find( const char *str, size_type index, size_type length ):返回str在字符串中第一次出現(xiàn)的位置(從index開始查找,長度為length),如果沒找到就返回string::npos。
size_type find( char ch, size_type index ):返回字符ch在字符串中第一次出現(xiàn)的位置(從index開始查找),如果沒找到就返回string::npos。
以上的查找功能都是按照從前往后的順序進行查找,如果想要按照從后往前的順序進行查找的話,可以用"rfind"語句。
2、size_type find_first_of ( const string& str, size_type pos = 0 )
功能介紹:返回str中任意字符在字符串中第一次出現(xiàn)的位置,從位置0開始查找。
類似功能的函數(shù)有以下幾個。
size_type find_first_of ( const char* s, size_type pos, size_t n )
size_type find_first_of ( const char* s, size_type pos = 0 )
size_type find_first_of ( char c, size_type pos = 0 )
3、find_first_not_of
功能與find_first_of()函數(shù)的功能正好相反。
4、find_last_of
與find_first_of()函數(shù)相比而言,其不同的地方在于:find_last_of()是找出最后一個相同的位置。
5、find_last_not_of
與find_last_of()功能函數(shù)正好相反。
四、其他方面的函數(shù)
1、string &insert(int p,const string &s)
功能介紹:在p位置插入字符串s
2、string &replace(int p, int n,const char *s)
功能介紹:刪除從p開始的n個字符,然后在p處插入字符串s
3、string &erase(int p, int n)
功能介紹:刪除p開始的n個字符,返回修改后的字符串
4、string substr(int pos, int n )
功能介紹:返回pos開始的n個字符組成的字符串
5、void swap(string &s2)
功能介紹:交換當前字符串與s2的值
6、string &append(const char *s)
功能介紹:把字符串s連接到當前字符串結尾
7、void push_back(char c)
功能介紹:當前字符串尾部加一個字符c
8、const char *data()/
功能介紹:返回一個非null終止的c字符數(shù)組,data():與c_str()類似,用于string轉const char*其中它返回的數(shù)組是不以空字符終止。
9、const char *c_str()
返回一個以null終止的c字符串,即c_str()函數(shù)返回一個指向正規(guī)C字符串的指針, 內容與本string串相同,用于string轉const char*
浙公網(wǎng)安備 33010602011771號