Chapter 13.特殊容器string

string簡介

string對象是一個特殊類型的容器,被設計用來操作字符串
與傳統的c-string不同,傳統的c-string是一個字符數組,而string對象屬於一個類,類裏面實現了大量的成員函數來更直觀地操作字符串,同時很多有用的方法與C++容器都有相同的接口
string類是basic_string類模板的一個實例,在<string>中定義如下:
typedef basic_string<char> string;

構造函數
1.string ( );
2.string ( const string& str );
3.string ( const string& str, size_t pos, size_t n = npos );//第pos後的n個字符[pos從1開始到str.size()]
4.string ( const char * s, size_t n );
5.string ( const char * s );
6.string ( size_t n, char c );
7.template<class InputIterator> string (InputIterator begin, InputIterator end);

eg:
  string s0 ("Initial string");
  // constructors used in the same order as described above:
  string s1;
  string s2 (s0);
  string s3 (s0, 8, 3);
  string s4 ("A character sequence", 6);
  string s5 ("Another character sequence");
  string s6 (10, 'x');
  string s7a (10, 42);//*對應ascii的十進制值
  string s7b (s0.begin(), s0.begin()+7);
  cout << "s1: " << s1 << "\ns2: " << s2 << "\ns3: " << s3;
  cout << "\ns4: " << s4 << "\ns5: " << s5 << "\ns6: " << s6;
  cout << "\ns7a: " << s7a << "\ns7b: " << s7b << endl;
Output:
s1: 
s2: iti
s3: str
s4: A char
s5: Another character sequence
s6: xxxxxxxxxx
s7a: **********
s7b: Initial
operator=
1.string& operator= ( const string& str );
2.string& operator= ( const char* s );
3.string& operator= ( char c );

Capacity:

empty Test if string is empty
size/length Return length of string
max_size Return maximum size of string
resize Change sizeResize string
capacity Return size of allocated storage
reserve Request a change in capacity
clear Clear string
//resize
1.void resize ( size_t n, char c );
2.void resize ( size_t n );

eg:
  string str ("I like to code in C");
  cout << str << endl;
  size_t sz=str.size();
  str.resize (sz+2,'+');
  cout << str << endl;
Output:
I like to code in C
I like to code in C++

//reserve

  string str;
  size_t filesize;
  ifstream file ("test.txt",ios::in|ios::ate);
  filesize=file.tellg();
  str.reserve(filesize);
  file.seekg(0);
  while (!file.eof())
  {
    str += file.get();
  }
  cout << str;

Element access:

operator[] Get character in string
at Get character in string

Modifiers:

operator+= Append to string
append Append to string
push_back Append character to string
assign Assign content to string
insert Insert into string
erase Erase characters from string
replace Replace part of string
swap
Swap contents with another string
//+=
1.string& operator+= ( const string& str );//string
2.string& operator+= ( const char* s );//c-string
3.string& operator+= ( char c );//charactor

//append
1.string& append ( const string& str );
2.string& append ( const string& str, size_t pos, size_t n );
//str中的第一個元素pos爲0,append範圍爲str [pos,n)
3.string& append ( const char* s, size_t n );
//複製s中的n個字符
4.string& append ( const char* s );
5.string& append ( size_t n, char c );
//n個character
6.template <class InputIterator>
string& append ( InputIterator first, InputIterator last );

eg:
	string app1("hello");
	string app2(" world");
2.
	app1.append(app2,0,app2.size());//複製[0,app.size())到app1
Output:
hello world
3.
	app1.append("C++",2);//複製兩個字符,即C+
Output:
helloC+
5.
	app1.append(6,'h');//複製6個'h'到app1後
Output:
hellohhhhh
//push_back
void push_back ( char c );
eg:
  string str;
  ifstream file ("test.txt",ios::in);
  while (!file.eof())
  {
    str.push_back(file.get());
  }
  cout << str;
//assign
1.string& assign ( const string& str );
2.string& assign ( const string& str, size_t pos, size_t n );
//str中的第一個元素pos爲0,assign範圍爲str [pos,n)
3.string& assign ( const char* s, size_t n );
4.string& assign ( const char* s );
5.string& assign ( size_t n, char c );
6.template <class InputIterator>
string& assign ( InputIterator first, InputIterator last );

eg:
2.
	string app1("hello");
	string app2(" world");
	app2.assign(app1,1,app1.size());//assign範圍爲[1,app1.size())
Output:
ello
//insert
1.string& insert ( size_t pos1, const string& str );
2.string& insert ( size_t pos1, const string& str, size_t pos2, size_t n );
3.string& insert ( size_t pos1, const char* s, size_t n);
4.string& insert ( size_t pos1, const char* s );
5.string& insert ( size_t pos1, size_t n, char c );
6.iterator insert ( iterator p, char c );
7.void insert ( iterator p, size_t n, char c );
8.template<class InputIterator>
void insert ( iterator p, InputIterator first, InputIterator last );

tips:
    pos1 & pos2都是從0開始
eg:
  string str="to be question";
              0123456789*123    //位置
  string str2="the ";
  string str3="or not to be";
               0123456789*123    //位置
  string::iterator it;

  // used in the same order as described above:1-8
  str.insert(6,str2);                 // to be (the )question        
  str.insert(6,str3,3,4);             // to be (not )the question    
  str.insert(10,"that is cool",8);    // to be not (that is )the question   
  str.insert(10,"to be ");            // to be not (to be )that is the question    
  str.insert(15,1,':');               // to be not to be(:) that is the question    
  it = str.insert(str.begin()+5,','); // to be(,) not to be: that is the question    
  str.insert (str.end(),3,'.');       // to be, not to be: that is the question(...)  
  str.insert (it+2,str3.begin(),str3.begin()+3); // (or )    
1.在str的6位置處插入str2
2.在str的6位置處插入str3的3位置向後4位的字符
3.在str的10位置處插入that is cool的前8個字符,即 that空is空
4.在10位置處插入const char*
5.在15位置處插入一個:
6.在iterator處插入一個,
7.在str的iterator處插入3個.
8.iterator範圍內的插入
//erase
1.string& erase ( size_t pos = 0, size_t n = npos );//erase掉pos後n個字符
2.iterator erase ( iterator position );
3.iterator erase ( iterator first, iterator last );

eg:
1.
  string str ("This is an example phrase.");
               0123456789*12345678
  string::iterator it;
  str.erase (10,8);
  cout << str << endl;        // "This is an phrase."
//replace
1.string& replace ( size_t pos1, size_t n1,   const string& str );
2.string& replace ( iterator i1, iterator i2, const string& str );
3.string& replace ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 );
4.string& replace ( size_t pos1, size_t n1,   const char* s, size_t n2 );
5.string& replace ( iterator i1, iterator i2, const char* s, size_t n2 );
6.string& replace ( size_t pos1, size_t n1,   const char* s );
7.string& replace ( iterator i1, iterator i2, const char* s );
8.string& replace ( size_t pos1, size_t n1,   size_t n2, char c );
9.string& replace ( iterator i1, iterator i2, size_t n2, char c );
10.template<class InputIterator>
string& replace ( iterator i1, iterator i2, InputIterator j1, InputIterator j2 );

eg:
  string base="this is a test string.";
  string str2="n example";
  string str3="sample phrase";
  string str4="useful.";
  // function versions used in the same order as described above:
  // Using positions:                 0123456789*123456789*12345
  string str=base;                // "this is a test string."
  str.replace(9,5,str2);          // "this is an example string."
  str.replace(19,6,str3,7,6);     // "this is an example phrase."
  str.replace(8,10,"just all",6); // "this is just a phrase."        複製6位
  str.replace(8,6,"a short");     // "this is a short phrase."       just a → a short
  str.replace(22,1,3,'!');        // "this is a short phrase!!!"


  // Using iterators:                      0123456789*123456789*
  string::iterator it = str.begin();   //  ^
  str.replace(it,str.end()-3,str3);    // "sample phrase!!!"
  str.replace(it,it+6,"replace it",7); // "replace phrase!!!"
  it+=8;                               //          ^
  str.replace(it,it+6,"is cool");      // "replace is cool!!!"
  str.replace(it+4,str.end()-4,4,'o'); // "replace is cooool!!!"
  it+=3;                               //             ^
  str.replace(it,str.end(),str4.begin(),str4.end());
                                       // "replace is useful."

String operations:

c_str Get C string equivalent
data Get string data
get_allocator Get allocator
copy Copy sequence of characters from string
find Find content in string
rfind Find last occurrence of content in string
find_first_of Find character in string
find_last_of Find character in string from the end
find_first_not_of Find absence of character in string
find_last_not_of Find absence of character in string from the end
substr Generate substring
compare Compare strings
string::npos等於str.max_size()+1,即string最大的長度4294967294+1

//find    正向查找
//查找成功時返回所在位置,失敗返回string::npos的值
1.size_t find ( const string& str, size_t pos = 0 ) const;    以另一個str來作find
2.size_t find ( const char* s, size_t pos, size_t n ) const;  以一個const char*的pos位置開始的n個字符串來find pos從0開始到str.size()-1
3.size_t find ( const char* s, size_t pos = 0 ) const;        以一個const char*的pos位置開始來作find
4.size_t find ( char c, size_t pos = 0 ) const;               以一個char的pos位置開始來作find

//rfind  反向查找
1.size_t rfind ( const string& str, size_t pos = npos ) const;
2.size_t rfind ( const char* s, size_t pos, size_t n ) const;
3.size_t rfind ( const char* s, size_t pos = npos ) const;
4.size_t rfind ( char c, size_t pos = npos ) const;

//find_first_of    正向查找
查找在string中出現的任何字符,返回第一次出現的位置
1.size_t find_first_of ( const string& str, size_t pos = 0 ) const;
2.size_t find_first_of ( const char* s, size_t pos, size_t n ) const;//從pos開始查找當前串中第一個在s的前n個字符組成的數組裏的字符的位置。查找失敗返回string::npos
3.size_t find_first_of ( const char* s, size_t pos = 0 ) const;
4.size_t find_first_of ( char c, size_t pos = 0 ) const;

//find_first_not_of
//從當前串中查找第一個不在串s中的字符出現的位置,失敗返回string::npos
1.size_t find_first_not_of ( const string& str, size_t pos = 0 ) const;
2.size_t find_first_not_of ( const char* s, size_t pos, size_t n ) const;
3.size_t find_first_not_of ( const char* s, size_t pos = 0 ) const;
4.size_t find_first_not_of ( char c, size_t pos = 0 ) const;

//find_last_of    反向查找
1.size_t find_last_of ( const string& str, size_t pos = npos ) const;
2.size_t find_last_of ( const char* s, size_t pos, size_t n ) const;
3.size_t find_last_of ( const char* s, size_t pos = npos ) const;
4.size_t find_last_of ( char c, size_t pos = npos ) const;

//find_last_not_of
1.size_t find_last_not_of ( const string& str, size_t pos = npos ) const;
2.size_t find_last_not_of ( const char* s, size_t pos, size_t n ) const;
3.size_t find_last_not_of ( const char* s, size_t pos = npos ) const;
4.size_t find_last_not_of ( char c, size_t pos = npos ) const;

//c_str()返回一個字符數組+'\0'
//data()返回一個字符數組

//copy()
size_t copy ( char* s, size_t n, size_t pos = 0) const;
eg:
  char buffer[20];
  string str ("Test string...");
               0123456789*123  
  size_t length=str.copy(buffer,6,5);//從5位置處copy6個字符到buffer中
  buffer[length]='\0';
  cout << buffer << endl;
Output:
string
//substr()
string substr ( size_t pos = 0, size_t n = npos ) const;
eg:
	string str("hello C++");
	OutputDebugString(str.substr(6,3).c_str());
//compare
1.int compare ( const string& str ) const;
2.int compare ( const char* s ) const;
3.int compare ( size_t pos1, size_t n1, const string& str ) const;
4.int compare ( size_t pos1, size_t n1, const char* s) const;
5.int compare ( size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2 ) const;
6.int compare ( size_t pos1, size_t n1, const char* s, size_t n2) const;

eg:
  string str1 ("green apple");
  string str2 ("red apple");
  if (str1.compare(str2) != 0)
    cout << str1 << " is not " << str2 << "\n";
  if (str1.compare(6,5,"apple") == 0)
    cout << "still, " << str1 << " is an apple\n";
  if (str2.compare(str2.size()-5,5,"apple") == 0)
    cout << "and " << str2 << " is also an apple\n";
  if (str1.compare(6,5,str2,4,5) == 0)
    cout << "therefore, both are apples\n";
Output:
green apple is not red apple
still, green apple is an apple
and red apple is also an apple
therefore, both are apples

getline
1.istream& getline ( istream& is, string& str, char delim );//遇到字符delim結束,並丟棄delim 
2.istream& getline ( istream& is, string& str );//遇到字符'\n'結束,並丟棄'\n' 

string str;
getline(cin,str,'a');//遇到字符'a'結束,並丟棄'a'
cout << str << endl;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章