Detailed explanation of C++STL (I) -- sring class
Content outline of this meeting:
1, How string is defined
The string class implements the overloading of multiple constructors. The commonly used constructors are as follows:
string(); //Construct an empty string string(const char* s); //Copy the character sequence indicated by s string(const char* s, size_t n); //Copy the first n characters of the character sequence indicated by s string(size_t n, char c); //Generate a string of n c characters string(const string& str); //Generate a copy of str string(const string& str, size_t pos, size_t len = npos); //Copy the part of str that starts at the character position pos and spans len characters
Use example:
string s1; //Construct an empty string string s2("hello string"); //Copy "hello string" string s3("hello string", 3); //Copy the first three characters of "hello string" string s4(10, 's'); //Generate a string of 10's' characters string s5(s2); //Create a copy of s2 string s6(s2, 0, 4); //Copy the part of s2 that starts at character position 0 and spans 4 characters
2, Insertion of string
1. Using push_back for tail interpolation
void push_back (char c);
#include <iostream> #include <string> using namespace std; int main() { string s; s.push_back('C'); s.push_back('S'); s.push_back('D'); s.push_back('N'); cout << s << endl; //CSDN return 0; }
2. Insert using insert
string& insert (size_t pos, const string& str);
string& insert (size_t pos, const char* s);
iterator insert (iterator p, char c);
#include <iostream> #include <string> using namespace std; int main() { string s("C"); //C //insert(pos, str) inserts the string str at the pos position s.insert(1, "S"); //CS //insert(pos, string) inserts a string object at the pos position string t("D"); s.insert(2, t); //CSD //insert(pos, char) inserts the character char at the pos position s.insert(s.end(), 'N'); //CSDN cout << s << endl; //CSDN return 0; }
3, string splicing
Use the append function to splice string s:
string& append (const string& str);
string& append (const char* s);
string& append (size_t n, char c);
#include <iostream> #include <string> using namespace std; int main() { string s1("I"); string s2(" like"); //append(string) completes the splicing of two string objects s1.append(s2); //I like //append(str) completes the splicing of string object and string str s1.append(" C++"); //I like C++ //append(n, char) concatenates n char characters behind a string object s1.append(3, '!'); //I like C++!!! cout << s1 << endl; //I like C++!!! return 0; }
4, Deletion of string
1. Using pop_back for tail deletion
void pop_back();
#include <iostream> #include <string> using namespace std; int main() { string s("C++"); s.pop_back(); s.pop_back(); cout << s << endl; //C return 0; }
2. Delete using erase
string& erase (size_t pos = 0, size_t len = npos);
iterator erase (iterator p);
iterator erase (iterator first, iterator last);
#include <iostream> #include <string> using namespace std; int main() { string s("I like C++!!!"); //erase(pos, n) deletes the n characters starting at the pos position s.erase(8, 5); //I like C //erase(pos) deletes the character at the pos position s.erase(s.end()-1); //I like //Post all characters s.erase(s.begin() + 1, s.end()); //I cout << s << endl; //I return 0; }
5, string lookup
1. Use the find function to forward search for the first match
size_t find (const string& str, size_t pos = 0) const;
size_t find (const char* s, size_t pos = 0) const;
size_t find (char c, size_t pos = 0) const;
#include <iostream> #include <string> using namespace std; int main() { string s1("http://www.cplusplus.com/reference/string/string/find/"); //find(string) searches forward for the first location that matches the string object string s2("www"); size_t pos1 = s1.find(s2); cout << pos1 << endl; //7 //find(str) searches forward for the first position that matches the string str char str[] = "cplusplus.com"; size_t pos2 = s1.find(str); cout << pos2 << endl; //11 //find(char) searches forward for the first position that matches the character char size_t pos3 = s1.find(':'); cout << pos3 << endl; //4 return 0; }
2. Use the rfind function to reverse the search for the first match
size_t rfind (const string& str, size_t pos = npos) const;
size_t rfind (const char* s, size_t pos = npos) const;
size_t rfind (char c, size_t pos = npos) const;
#include <iostream> #include <string> using namespace std; int main() { string s1("http://www.cplusplus.com/reference/string/string/find/"); //rfind(string) reverses the search for the first location that matches the string object string s2("string"); size_t pos1 = s1.rfind(s2); cout << pos1 << endl; //42 //rfind(str) reverses the search for the first position that matches the string str char str[] = "reference"; size_t pos2 = s1.rfind(str); cout << pos2 << endl; //25 //rfind(char) reverses the search for the first position that matches the character char size_t pos3 = s1.rfind('/'); cout << pos3 << endl; //53 return 0; }
6, Comparison of string s
Use the compare function to complete the comparison:
int compare (const string& str) const;
int compare (size_t pos, size_t len, const string& str) const;
int compare (size_t pos, size_t len, const string& str, size_t subpos, size_t sublen) const;
Comparison rules:
1. If the value of the first mismatched character in the comparison string is small, or all comparison characters match, but the comparison string is short, a value less than 0 will be returned.
2. If the value of the first mismatched character in the comparison string is large, or all comparison characters match, but the comparison string is long, a value greater than 0 will be returned.
3. If the two strings compared are equal, 0 is returned.
#include <iostream> #include <string> using namespace std; int main() { string s1("hello world"); string s2("hello CSDN"); //Comparison between "hello world" and "hello CSDN" cout << s1.compare(s2) << endl; //1 //"ell" and "hello CSDN" comparison cout << s1.compare(1, 3, s2) << endl; //-1 //"Hello" and "hello" comparison cout << s1.compare(0, 4, s2, 0, 4) << endl; //0 return 0; }
Note: in addition to supporting the comparison between string classes, the compare function also supports the comparison between string classes and strings.
7, Replacement of string
Use the replace function to replace a string:
string& replace (size_t pos, size_t len, const char* s);
string& replace (size_t pos, size_t len, size_t n, char c);
#include <iostream> #include <string> using namespace std; int main() { string s("hello world"); //replace(pos, len, str) replaces the len characters starting at the pos position with the string str s.replace(6, 4, "CSDN"); //hello CSDNd //replace(pos, len, n, char) replaces the len characters starting at the pos position with n char characters s.replace(10, 1, 3, '!'); //hello CSDN!!! cout << s << endl; return 0; }
8, string exchange
Use the swap function to complete the exchange of two string classes:
void swap (string& x, string& y);
void swap (string& str);
#include <iostream> #include <string> using namespace std; int main() { string s1("hello"); string s2("CSDN"); //Swap s1 and s2 using the member function swap of the string class s1.swap(s2); cout << s1 << endl; //CSDN cout << s2 << endl; //hello //Swap s1 and s2 using the nonmember function swap swap(s1, s2); cout << s1 << endl; //hello cout << s2 << endl; //CSDN return 0; }
9, Size and capacity of string
1. Use the size function or length function to get the number of currently valid characters
size_t size() const;
size_t length() const;
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); cout << s.size() << endl; //4 cout << s.length() << endl; //4 return 0; }
2. Use Max_ The size function gets the number of characters that a string object can contain
size_t max_size() const;
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); cout << s.max_size() << endl; //4294967294 return 0; }
3. Use the capacity function to get the size of the storage space allocated by the current object
size_t capacity() const;
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); cout << s.capacity() << endl; //15 return 0; }
4. Use resize to change the number of valid characters of the current object
void resize (size_t n);
void resize (size_t n, char c);
resize rule:
1. When n is greater than the current size of the object, expand the size to N, and the expanded character is c. if c is not given, it defaults to '\ 0'.
2. When n is smaller than the current size of the object, reduce the size to n.
#include <iostream> #include <string> using namespace std; int main() { string s1("CSDN"); //Resize (n) when n is greater than the current size of the object, expand the size to N, and the expanded character is' \ 0 'by default s1.resize(20); cout << s1 << endl; //CSDN cout << s1.size() << endl; //20 cout << s1.capacity() << endl; //31 string s2("CSDN"); //Resize (n, char) when n is greater than the current size of the object, expand the size to N, and the expanded character is char s2.resize(20, 'x'); cout << s2 << endl; //CSDNxxxxxxxxxxxxxxxx cout << s2.size() << endl; //20 cout << s2.capacity() << endl; //31 string s3("CSDN"); //Resize (n) when n is smaller than the current size of the object, reduce the size to n s3.resize(2); cout << s3 << endl; //CS cout << s3.size() << endl; //2 cout << s3.capacity() << endl; //15 return 0; }
Note: if the given n is greater than the current capacity of the object, the capacity will also be expanded according to its own growth rules.
5. Use reserve to change the capacity of the current object
void reserve (size_t n = 0);
reserve rule:
1. When n is greater than the current capacity of the object, expand the capacity to N or greater than n.
2. Do nothing when n is less than the current capacity of the object.
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); cout << s << endl; //CSDN cout << s.size() << endl; //4 cout << s.capacity() << endl; //15 //reverse(n) when n is greater than the current capacity of the object, expand the capacity of the current object to N or greater than n s.reserve(20); cout << s << endl; //CDSN cout << s.size() << endl; //4 cout << s.capacity() << endl; //31 //reverse(n) do nothing when n is less than the current capacity of the object s.reserve(2); cout << s << endl; //CDSN cout << s.size() << endl; //4 cout << s.capacity() << endl; //31 return 0; }
Note: this function has no effect on the size of the string and cannot change its content.
6. Use clear to delete the contents of the object. After deletion, the object becomes an empty string
void clear();
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); //clear() deletes the contents of the object, which becomes an empty string s.clear(); cout << s << endl; //Empty string return 0; }
7. Use empty to determine whether the object is empty
bool empty() const;
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); cout << s.empty() << endl; //0 //clear() deletes the contents of the object, which becomes an empty string s.clear(); cout << s.empty() << endl; //1 return 0; }
10, Access to elements in string
1. [] + subscript
because the string class overloads the [] operator, we can directly use the [] + subscript to access the elements in the object. And the overload uses reference return, so we can modify the element at the corresponding position through [] + subscript.
char& operator[] (size_t pos);
const char& operator[] (size_t pos) const;
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); //[] + subscript access object element for (size_t i = 0; i < s.size(); i++) { cout << s[i]; } cout << endl; //[] + subscript modifies the content of the object element for (size_t i = 0; i < s.size(); i++) { s[i] = 'x'; } cout << s << endl; //xxxx return 0; }
2. Using at to access elements in an object
because the at function is also a reference return, we can also modify the element at the corresponding position through the at function.
char& at (size_t pos);
const char& at (size_t pos) const;
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); for (size_t i = 0; i < s.size(); i++) { //at(pos) accesses the element of the pos location cout << s.at(i); } cout << endl; for (size_t i = 0; i < s.size(); i++) { //at(pos) accesses the element at the pos location and modifies it s.at(i) = 'x'; } cout << s << endl; //xxxx return 0; }
3. Use the scope for to access elements in an object
special attention should be paid: if the element of the object needs to be modified through the range for, the type of variable e used to receive the element must be reference type, otherwise e is only a copy of the object element, and the modification of e will not affect the element of the object.
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); //Using the scope for to access object elements for (auto e : s) { cout << e; } cout << endl; //CSDN //Use the scope for to access object elements and modify them for (auto& e : s) //The element of the object to be modified, e must be a reference type { e = 'x'; } cout << s << endl; //xxxx return 0; }
4. Using iterators to access elements in objects
#include <iostream> #include <string> using namespace std; int main() { string s("CSDN"); //Accessing object elements using iterators string::iterator it1 = s.begin(); while (it1 != s.end()) { cout << *it1; it1++; } cout << endl; //CSDN //Use iterators to access and modify object elements string::iterator it2 = s.begin(); while (it2 != s.end()) { *it2 += 1; it2++; } cout << s << endl; //DTEO return 0; }
11, Use of operators in string
1,operator=
the = operator is overloaded in the string class. The overloaded = operator supports the assignment of string class, string and character.
#include <iostream> #include <string> using namespace std; int main() { string s1; string s2("CSDN"); //Support assignment of string class s1 = s2; cout << s1 << endl; //CSDN //Support string assignment s1 = "hello"; cout << s1 << endl; //hello //Support character assignment s1 = 'x'; cout << s1 << endl; //x return 0; }
2,operator+=
the + = operator is overloaded in the string class. The overloaded + = operator supports compound assignment of string class, string and character.
#include <iostream> #include <string> using namespace std; int main() { string s1; string s2("hello"); //Support compound assignment of string class s1 += s2; cout << s1 << endl; //hello //Support compound assignment of strings s1 += " CSDN"; cout << s1 << endl; //hello CSDN //Support compound assignment of characters s1 += '!'; cout << s1 << endl; //hello CSDN! return 0; }
3,operator+
the + operator is overloaded in the string class. The overloaded + operator supports the following types of operations:
string class + string class
string class + string
string + string class
string class + character
character + string class
After they are added, they all return a string class object.
#include <iostream> #include <string> using namespace std; int main() { string s; string s1("super"); string s2("man"); char str[] = "woman"; char ch = '!'; //String class + string class s = s1 + s2; cout << s << endl; //superman //String class + string s = s1 + str; cout << s << endl; //superwoman //String + string class s = str + s1; cout << s << endl; //womansuper //string class + character s = s1 + ch; cout << s << endl; //super! //Character + string class s = ch + s1; cout << s << endl; //!super return 0; }
4. Operator > > and operator<<
the > > and < < operators are also overloaded in the string class, which is why we can directly use > > and < < to input and output the string class.
istream& operator>> (istream& is, string& str);
ostream& operator<< (ostream& os, const string& str);
#include <iostream> #include <string> using namespace std; int main() { string s; cin >> s; //input cout << s << endl; //output return 0; }
5,relational operators
the string class also overloads a series of relational operators, which are = =,! =, <, < =, >, > =. The overloaded relational operators support the relationship comparison between string classes, between string classes, and between strings.
#include <iostream> #include <string> using namespace std; int main() { string s1("abcd"); string s2("abde"); cout << (s1 > s2) << endl; //0 cout << (s1 < s2) << endl; //1 cout << (s1 == s2) << endl; //0 return 0; }
Note: these overloaded relational comparison operators compare the ASCII values of the corresponding characters.
12, Iterator related functions in string
1. Functions related to forward iterators
begin function: returns an iterator that points to the first character of a string.
Function prototype:
iterator begin();
const_iterator begin() const;
End function: returns an iterator pointing to the end character of the string, that is' \ 0 '.
Function prototype:
iterator end();
const_iterator end() const;
Use example:
#include <iostream> #include <string> using namespace std; int main() { string s("hello string"); //Forward iterator string::iterator it = s.begin(); while (it != s.end()) { cout << *it; it++; } cout << endl; //hello string return 0; }
2. Functions related to inverse iterators
rbegin function: returns the inverse iterator pointing to the last character of the string.
Function prototype:
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
rend function: returns the inverse iterator pointing to the theoretical element before the first character of the string.
Function prototype:
reverse_iterator rend();
const_reverse_iterator rend() const;
Use example:
#include <iostream> #include <string> using namespace std; int main() { string s("hello string"); //reverse iterator string::reverse_iterator rit = s.rbegin(); while (rit != s.rend()) { cout << *rit; rit++; } cout << endl; //gnirts olleh return 0; }
13, Conversion between string and string
1. Convert string to string
converting a string into a string is very simple, which was mentioned earlier when talking about the definition of string.
#include <iostream> #include <string> using namespace std; int main() { //Mode 1 string s1("hello world"); //Mode 2 char str[] = "hello world"; string s2(str); cout << s1 << endl; //hello world cout << s2 << endl; //hello world return 0; }
2. Use c_str or data converts a string to a string
const char* c_str() const;
const char* data() const;
difference:
- In C++98, c_str() returns const char * type, and the returned string will end with a null character.
- In C++98, data() returns const char * type, and the returned string does not end with a null character.
- But in the C++11 version, c_str() is used in the same way as data().
#include <iostream> #include <string> using namespace std; int main() { string s("hello world "); const char* str1 = s.data(); const char* str2 = s.c_str(); cout << str1 << endl; cout << str2 << endl; return 0; }
14, Extraction of substring of string
1. Use the substr function to extract the substring in the string
string substr (size_t pos = 0, size_t len = npos) const;
#include <iostream> #include <string> using namespace std; int main() { string s1("abcdef"); string s2; //substr(pos, n) extracts the sequence of n characters from the pos position as the return value s2 = s1.substr(2, 4); cout << s2 << endl; //cdef return 0; }
2. Use the copy function to copy the substring of string into the character array
size_t copy (char* s, size_t len, size_t pos = 0) const;
#include <iostream> #include <string> using namespace std; int main() { string s("abcdef"); char str[20]; //copy(str, n, pos) copies the n characters from the pos position to the str string size_t length = s.copy(str, 4, 2); //The copy function will not append '\ 0' at the end of the copied content, which needs to be added manually str[length] = '\0'; cout << str << endl; //dcef return 0; }
15, getline function in string
we know that when using > > for input operation, when > > reads spaces, it will stop reading. Based on this, we will not be able to use > > to read a string containing spaces into a string object.
#include <iostream> #include <string> using namespace std; int main() { string s; cin >> s; //Input: hello CSDN cout << s << endl; //Output: hello return 0; }
at this time, we need to use the getline function to read a string containing spaces.
Usage 1:
istream& getline (istream& is, string& str);
the getline function stores the characters extracted from is in str until the newline '\ n' is read.
#include <iostream> #include <string> using namespace std; int main() { string s; getline(cin, s); //Input: hello CSDN cout << s << endl; //Output: hello CSDN return 0; }
Usage 2:
istream& getline (istream& is, string& str, char delim);
the getline function stores the characters extracted from is in str until the delimiter delim or newline '\ n' is read.
#include <iostream> #include <string> using namespace std; int main() { string s; getline(cin, s, 'D'); //Input: hello CSDN cout << s << endl; //Output: hello CS return 0; }
Offer a complete mind map:
Thanks for reading!