STD: String
The reason why the char * string is discarded and the string class in the C ++ standard library is used is because it is compared with the former, and does not have to worry about whether the memory is sufficient, the string length, and so on. It also appears as a class, the integrated operation functions are sufficient to meet our needs in most cases (or even 100%. We can use = for the value assignment operation, = for comparison, + for concatenation (isn't it easy ?). We can think of it as the basic data type of C ++.
The standard template library (STL) provides a STD: string class, which is a special feature of STD: basic_string. It is a container class and can be used as a string as a normal type, comparison, connection, traversal, STL algorithm, copying, assignment, and other operations are supported. This class is defined in the header file <string>.
# Include <string> // note that string. h string. H is not the C string header file.
1. Declare a C ++ string
STD: string class Constructor
It is easy to declare a string variable:
String STR;
In this way, we declare a string variable, but since it is a class, there are constructors and destructor. The preceding Declaration does not include any parameters, so the default constructor of string is used directly. What this function does is to initialize STR as an empty string. The constructor and destructor of the string class are as follows:
A) string S (); // generate an empty string s
B) string S (STR) // copy the constructor to generate a replica string (const string & Str) of Str)
C) string S (STR, stridx) // use the "beginning with stridx" in the STR string as the initial value of the string.
D) string S (const string & STR, size_type POs, strlen) // use the part of the string STR that "starts from POs and has a maximum length of strlen" as the initial value of the string.
E) string S (const char * s) // use the C string as the initial value of S.
F) string S (const char * CSTR, size_type N) // use the first n characters of string STR as the initial value of string S.
G) string S (INT num, char c) // generate a string containing num C characters
H) string S (beg, end) // use the characters in the interval beg; end (excluding end) as the initial values of string S.
I) S .~ String () // destroy all characters and release the memory
It's easy. I will not explain it.
If the constructed string is too long to be expressed, the length_error exception is thrown.
2. String operation functions
Here is the focus of C ++ strings. I will first list various operation functions. People who do not like to read all functions can find their favorite functions here, let's look at his detailed explanation later.
A) =, assign () // assign a new value
B) Swap () // exchanges the content of two strings
C) + =, append (), push_back () // Add characters at the end
D) insert () // insert characters
E) Erase (INT nstart, int nend) // Delete the nstart-nend Position Character
F) Clear () // Delete All characters
G) Replace () // replace character
H) + // concatenate strings
I) = ,! =, <, <=,>, >=, Compare () // compare strings
J) size (), length () // number of returned characters
K) max_size () // maximum number of returned characters
L) Empty () // determines whether the string is null.
M) Capacity () // returns the character capacity before the reallocation
N) Reserve () // retain a certain amount of memory to accommodate a certain number of characters
O) [], at () // access a single character
P)>, Getline () // read a value from stream
Q) <// write the value to stream
R) Copy () // assign a value to a c_string
S) c_str () // return the content as c_string
T) data () // returns the content in the form of a character array
U) substr () // returns a substring.
V) search functions
W) begin () end () // provides iterator support similar to STL
X) rbegin () rend () // reverse iterator
Y) get_allocator () // return to the Configurator
The following details:
Conversion of 2.1 C ++ strings and C strings
The c_string method provided by C ++ is to use data (), c_str (), and copy (), where data () returns the string content in the form of a character array, but does not add ''. C_str () returns an array of characters ending with '', while copy () copies or writes the content of the string to an existing c_string or character array. The C ++ string does not end. I suggest using C ++ strings in a program unless you have to use c_string. As it is only a brief introduction, a detailed introduction is skipped. Anyone who wants to know more about the precautions during use can leave a message (to my inbox ). I will explain it in detail.
2.2 size and capacity functions
There are three types of C ++ character strings:
A) Number of existing characters. The functions are size () and length (). They are equivalent. Empty () is used to check whether the string is null.
B) max_size () refers to the maximum number of characters that can be contained in the current C ++ string. It is likely to be related to machine restrictions or the size of continuous memory in the position of the string. We generally don't need to care about him. It should be enough for us. However, if it is not enough, an length_error exception will be thrown.
C) Capacity () specifies the maximum number of characters that a string can contain before the memory is reassigned. Another thing to note here is the reserve () function, which re-allocates the memory for the string. The size of the reallocation is determined by the parameter. The default parameter is 0. At this time, the unforced reduction of the string is performed.
It is also necessary to repeat the problem of converting C ++ strings and C strings. Many people will encounter such problems, your own program needs to call others' functions and classes (such as the database connection function connect (char *, char *), but others' function parameters use the char * format, we know that the character array returned by c_str () and data () is owned by this string, so it is a const char *. to be used as a parameter of the function mentioned above, it must also be copied to a char *, but our principle is that the C string is not used. Then, our processing method is: if this function does not modify the content of the parameter (that is, char *), we can connect (char *) USERID. c_str (),
(Char *) passwd. c_str (), but it is dangerous at this time, because the converted string can be modified (you can try it yourself if you are interested ), so I stress that the parameter must be copied to a char * unless it is modified during function call. Of course, the more secure way is to copy everything to a char. At the same time, we also pray that the experts who still use the C string for programming (say they are not a good expert at all, maybe they will start programming when we are still wearing kaixiao pants, haha ...) Write Functions are more standardized, so we do not have to perform forced conversion.
2.3 element access
We can use the subscript operator [] and function at () to access the characters contained in the element. However, it should be noted that the operator [] does not check whether the index is valid (valid index 0 ~ Str. Length (). If the index fails, it will cause undefined behavior. At () checks. If the index is invalid when at () is used, an out_of_range exception is thrown.
The const string a; operator [] is still valid for the index value of A. Length (), and its return value is ''. In other cases, the. Length () index is invalid. Example:
Const string CSTR ("const string ");
String STR ("string ");
STR [3]; // OK
Str. At (3); // OK
STR [100]; // undefined behavior
Str. At (100); // throw out_of_range
STR [Str. Length ()] // undefined behavior
CSTR [CSTR. Length ()] // return''
Str. At (Str. Length (); // throw out_of_range
CSTR. At (CSTR. Length () // throw out_of_range
I do not agree with the following reference or pointer assignment:
Char & R = s [2];
Char * P = & S [3];
This is because R and P are invalid immediately after a reallocation. The method to avoid this problem is not to use it.
Traverse all characters, which can be completed by a C-style index or STL iterator (if no modification is required, use const_iterator ).
STD: string name = "Marius ";
For (size_t I = 0; I <name. Length (); ++ I)
STD: cout <name [I];
For (STD: String: const_iterator CIT = Name. Begin (); CIT! = Name. End (); ++ CIT)
STD: cout <* cit;
For (STD: String: iterator it = Name. Begin (); it! = Name. End (); ++ it)
* It = toupper (* it );
2.4 comparison functions
C ++ strings support common comparison operators (>,>=, <,<=, == ,! =), Or even comparison between string and C-string (such as STR <"hello "). When using the operators>, >=, <, <=, and <=, the characters are compared alphabetically according to the "current character feature. The character before the dictionary sorting is small, and the comparison order is from the beginning to the back. When an unequal character is encountered, the size of the two strings is determined based on the comparison results of the two characters at the position. At the same time, string ("aaaa") <string (AAAAA ).
Another powerful comparison function is the member function compare (). It supports multi-parameter processing and comparison with index values and length locating substrings. Return an integer to indicate the comparison result. The returned value is 0-equal> 0-greater than <0-less. Example:
String S ("ABCD ");
S. Compare ("ABCD"); // return 0
S. Compare ("dcba"); // return a value smaller than 0
S. Compare ("AB"); // return a value greater than 0
S. Compare (s); // equal
S. Compare (, S,); // use "AB" and "cd" to compare values smaller than zero.
S. Compare (, "BCX", 2); // compare it with "BC" and "BC.
How is it? Full functions! What? Cannot satisfy your appetite? Well, there is a more personalized comparison algorithm. First, let's give a note that we use the STL comparison algorithm. What? Do you know nothing about STL? You need to repair it again!
2.5 change content
This is a large part of string operations.
First, assign values. The first assign value method is of course using the operator =. The new values can be string (for example, s = NS) and c_string (for example, s = "gaint ") or even a single character (for example, s = 'J '). You can also use the member function assign (), which allows you to assign values to strings more flexibly. Let's give an example:
S. Assign (STR); // not to mention
S. Assign (STR,); // If STR is "iamangel", "AMA" is assigned to the string.
S. Assign (STR, 2, string: NPOs); // assign the string 'str' to s from index 2 to the end.
S. Assign ("gaint"); // do not mention
S. Assign ("Nico", 5); // assign 'n' 'I C' O ''To the string
S. Assign (5, 'x'); // assign five X to the string.
There are three methods to clear the string: S = ""; S. Clear (); S. Erase (); (I think it is easier to give examples to others than to speak !).
String provides many functions for insert, erase, replace, and adding characters.
First, add characters (in this example, add on the tail). functions include + =, append (), and push_back (). Example:
S + = STR; // Add a string
S + = "My name is jiayp"; // Add a C string
S + = 'a'; // Add a character
S. append (STR );
S. append (STR,); // it does not explain the interpretation of the function parameter assign.
S. append (STR, 2, string: NPOs) // not explained
S. append ("My name is jiayp ");
S. append ("Nico", 5 );
S. append (5, 'x ');
2.5.1 insert other elements at the end of the string.
S. push_back ('A'); // This function can only add a single character to understand STL easily.
2.5.2 insert a string or character at a specified position.
Maybe you need to insert a string somewhere in the middle of the string. At this time, you can use the insert () function. This function requires you to specify an index for the Insert Location, the inserted string is placed behind this index.
S. insert (0, "my name ");
S. insert (1, STR );
This form of insert () function does not support the input of a single character. At this time, a single character must be written as a string (disgusting ). Since you are disgusted, You have to continue reading the following: To insert a single character, the insert () function provides two overloaded functions for inserting a single character: insert (size_type index, size_type num, Chart C) and insert (iterator POs, size_type num, Chart C ). Size_type is an unsigned integer and iterator is char *. Therefore, you cannot call the insert function as follows: insert,
'J'); which one will the first parameter be converted? So you must write: insert (string: size_type) 0, 1, 'J ')! The second form indicates the use of the iterator to insert characters, which will be mentioned later. By the way, many operations on string use the STL iterator, And He tries his best to keep it close to STL.
There are also several ways to delete the function erase !), There are also several Replace () replace functions. For example:
String S = "il8n ";
S. Replace (, "nternationalizatio"); // Replace the two values starting from Index 1 with the c_string
2.5.3 delete a part of a string.
S. Erase (13); // delete all data starting from Index 13
S. Erase (); // Delete 5 from index 7
2.6 extract substrings and string connections
The substring function is substr (). The format is as follows:
S. substr (); // returns all content of S.
S. substr (11); // substring after index 11
S. substr (5, 6); // 6 characters starting from index 5
The function that combines the two strings is +. (If you do not understand, call 120)
2.7 input/output operations
1.> Read a string from the input stream.
2. <write a string to the output stream.
Another function is Getline (). It reads a line of content from the input stream until it encounters a branch character or reaches the end of the file.
2.8 search and search
STD: String-type lookup Function
There are many search functions and powerful functions, including:
Find ()
Rfind ()
Find_first_of ()
Find_last_of ()
Find_first_not_of ()
Find_last_not_of ()
These functions return the index of the first character in the character range that meets the search criteria. If no target is found, NPOs is returned. Parameters of all functions are described as follows:
The first parameter is the searched object. The second parameter (optional) indicates the Search Start index in the string, and the third parameter (optional) indicates the number of characters in the search. It is relatively simple. If you don't want to understand it, you can give it to me. I will answer it carefully. Of course, more powerful STL search will be mentioned later.
Finally, let's talk about the meaning of NPOs. The string: NPOs type is string: size_type. Therefore, once an index needs to be compared with NPOs, the index value must be string: size) type. In more cases, we can directly compare the function with NPOs (for example, if (S. find ("jia") = string: NPOs )).
3.1 Use STL Algorithms
STD: string name = "Marius ";
// Make all strings uppercase
STD: Transform (name. Begin (), name. End (), name. Begin (), toupper );
STD: string name = "Marius ";
// Sort strings in ascending order
STD: Sort (name. Begin (), name. End ());
STD: string name = "Marius ";
// Reverse the string
STD: reverse (name. Begin (), name. End ());
Bool iswhitespace (char ch)
{
ReturnCh = ''| CH = 'T' | CH = 'V' |
Ch = 'R' | CH = 'n ';
}
STD: string name = "Marius";
// Delete blank characters
STD: String: iterator newend = STD: remove_if (name. Begin (), name. End (), iswhitespace );
Name. Erase (newend );
STD: replacement function of the string class
Function 1:
STD: string & replace (size_type pos1, size_type N1, const STD: string & STR, size_type pos2 = 0, size_type n2 = NPOs );
Function: Use the STR string to replace the N1 characters starting from the position pos1 with the N2 characters starting from the position pos2.
It can be understood as follows: This function deletes all N1 characters of the current string starting from pos1, and then uses the entire STR string or N2 characters of STR starting from pos2, enter the position of pos1 in the current string.
Note: If the value of N1 or N2 exceeds the length of the corresponding string, the actual length is used as the standard and the access is not out of bounds.
Note:
A. If the position specified by pos1 exceeds the range of the current string, a STD: out_of_range exception is thrown. coredump is caused if no capture is performed.
B. If the position specified by pos2 exceeds the STR range of the replacement string, a STD: out_of_range exception is thrown. coredump is caused if no capture is performed.
Function 2:
STD: string & replace (size_type POs, size_type N1, const char * s, size_type N2 );
Function: Use the first N2 character of string s to replace the N1 character of the current string starting from the POs position.
It can be understood as follows: The function deletes all N1 characters of the current string starting from POs, and then fills in the current string with the first N2 characters of string S. Similar to the case where pos2 of function 1 is equal to 0, N2 must be specified, but there is also a slight difference. The following describes this difference.
Note:
A. If the position specified by the POs exceeds the range of the current string, a STD: out_of_range exception is thrown. If the position is not captured, coredump is thrown.
B. This function does not determine the size relationship between string S and N2. It strictly copies N2 characters from the starting position of S to the specified position. If the length indicated by N2 is beyond the range of S, it will read the memory space after s, possibly due to out-of-bounds memory access and coredump. However, N2 of function 1 can be out of the range. The actual length prevails.
Function 3:
STD: string & replace (size_type POs, size_type N1, const char * s );
Function: Use string s ending with ''to replace the N1 characters starting from the POs position of the current string.
It can be understood as follows: The function deletes all the N1 characters of the current string starting from POs, and then uses string s to start all the characters ending, enter the POs position in the current string.
Note: If the position specified by the POs exceeds the range of the current string, an STD: out_of_range exception is thrown. If the position is not captured, coredump is thrown.
Function 4:
STD: string & replace (size_type POs, size_type N1, size_type N2, char C );
Function: Replace the N1 characters of the current string starting from the POs position with N2 C characters.
It can be understood that the function deletes all N1 characters of the current string starting from POs, and then uses N2 C characters to enter the current string from the POs position.
Note: If the position specified by the POs exceeds the range of the current string, an STD: out_of_range exception is thrown. If the position is not captured, coredump is thrown.
Function 5:
STD: string & replace (iterator I1, iterator I2, const STD: string & Str );
Function: Use the STR string to replace the characters between the current string [I1, I2.
Function 6:
STD: string & replace (iterator I1, iterator I2, const char * s, size_type N );
Function: Use the first n characters of string s to replace the characters between the current string [I1, I2.
Function 7:
STD: string & replace (iterator I1, iterator I2, const char * s );
Function: Use string s ending with ''to replace the characters between the current string [I1, I2.
Function 8:
STD: string & replace (iterator I1, iterator I2, size_type N, char C );
Function: Replace the characters between the current string [I1, I2) with the characters represented by n c.
STD: Internal Type Definition of the string class
Typedef traits traits_type; |
Typedef typename traits: char_type value_type; |
Typedef size_t size_type; |
Typedef Allocator allocator_type; |
Typedef ptrdiff_t difference_type; |
Typedef Allocator allocator_type; |
Typedef Allocator allocator_type; |
Typedef Allocator allocator_type; |
Typedef chart & reference; typedef const chart & const_reference; typedef chart * pointer; typedef const chart * const_pointer; typedef pointer iterator; typedef const_pointer const_iterator; typedef: warning frequency; typedef
: Reverse_iterator const_reverse_iterator; static const size_type NPOs = static_cast (-1 );
STD: Value assignment operator of the string class
String & operator = (const char * s );
String & operator = (char C );
String & operator ++ = (const string & RHs );
String & operator ++ = (const char * s );
String & operator ++ = (char C );
String operator + (const string & LHS, const string & RHs );
String operator + (const char * LHS, const string & RHs );
String operator + (char LHS, const string & RHs );
String operator + (const string & LHS, const char * RHs );
String operator + (const string & LHS, char RHs );
STD: logical operator of the string class
Bool operator = (const string & LHS, const string & RHs );
Bool operator = (const char * LHS, const string & RHs );
Bool operator = (const string & LHS, const char * RHs );
Bool Operator! = (Const string & LHS, const string & RHs );
Bool Operator! = (Const char * LHS, const string & RHs );
Bool Operator! = (Const string & LHS, const char * RHs );
Bool operator <(const string & LHS, const string & RHs );
Bool operator <(const char * LHS, const string & RHs );
Bool operator <(const string & LHS, const char * RHs );
Bool operator> (const string & LHS, const string & RHs );
Bool operator> (const char * LHS, const string & RHs );
Bool operator> (const string & LHS, const char * RHs );
Bool operator <= (const string & LHS, const string & RHs );
Bool operator <= (const char * LHS, const string & RHs );
Bool operator <= (const string & LHS, const char * RHs );
Bool operator >=( const string & LHS, const string & RHs );
Bool operator >=( const char * LHS, const string & RHs );
Bool operator >=( const string & LHS, const char * RHs );
Istream & operator> (istream &, string &);
Ostream & operator <(ostream &, const string &);
Istream & Getline (istream &, string &, char delim = 'n ');