- string類的構造字符串
構造函數 |
描述 |
string(const char *s) |
將string對象初始化爲s指向的NBTS(null-terminated string) |
string(size_type n,char c) |
創建一個包含n個元素的string對象,其中每個元素都被初始化爲字符c |
string(const string & str) |
將一個string對象初始化爲string對象str(複製構造函數) |
string() |
創建一個默認的string對象,長度爲0(默認構造函數) |
[C++.Primer.Plus(第6版)中文版] |
P675還有5種 |
- string類的輸入
char info[100];
cin>>info; //read a word
cin.getline(info,100); //read a line,discard \n
cin.get(info,100); //read a line,leave \n in queue
string stuff;
cin>>stuff; // read a word;
getline(cin,stuff); // read a line,discard \n
- string版本的getline()將自動調整目標string對象的大小,使之剛好能夠存儲輸入的字符。
- 使用字符串
- 可以比較字符串,String類對全部6個關係運算符都進行了重載。
- 重載的find()方法
方法原型 |
描述 |
size_type find(const string &str, size_type pos = 0)const |
從字符串的pos位置開始,查找子字符串str。如果找到,則返回該子字符串首次出現時其首字符的索引;否則,返回string::opos |
size_type find(const char * s, size_type pos = 0)const |
從字符串的pos位置開始,查找子字符串s。如果找到,則返回該子字符串首次出現時其首字符的索引;否則,返回string::opos |
size_type find(const char * s, size_type pos = 0,size_type n) |
從字符串的pos位置開始,查找s的前n個字符組成的子字符串。如果找到,則返回該子字符串首次出現時其首字符的索引;否則,返回string::opos |
size_type find(char ch, size_type pos = 0)const |
從字符串的pos位置開始,查找字符ch。如果找到,則返回該字符首次出現的位置;否則,返回string::opos |
- string庫還提供了相關的方法,它們重載函數特徵標都與find函數方法相同:
- rfind():查找子字符串或字符最後一次出現的位置
- find_first_of():在字符串中查找參數中任何一個字符首次出現的位置。
- find_last_of():在字符串中查找參數中任何一個字符最後一次出現的位置。
- find_first_not_of():在字符串中查找第一個不包含在參數中的字符。
- find_last_not_of():在字符串中查找最後一個不包含在參數中的字符。
- 前面提到的string類看作是基於char類型的,事實上,string庫實際上是基於一個模板類的:
template<class charT,class traits = char _traits<charT>,
class Allocator = allocator<charT> >
basic_string{...};
//模板basic_string 有4個具體化,每個具體化都有一個typedef名稱:
typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
typedef basic_string<char16_t> u16string;
typedef basic_string<char32_t> u32string;