This is frequently used
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 ++.
Okay, go to the topic .........
First, to use the string type in our program, we must include the header file <string>. As follows:
# Include <string> // note that string. h string. H is not the C string header file.
1. Declare a C ++ string
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 copy of STR
C) string S (STR, stridx) // use the portion of the string 'start with stridx 'as the initial value of the string.
D) string S (STR, stridx, strlen) // take the part of the string 'strx' that begins with stridx and has a maximum length of strlen' as the initial value of the string.
E) string S (CSTR) // use the C string as the initial value of S.
F) string S (chars, chars_len) // use the character chars_len before the C string as the initial value of string S.
G) string S (Num, 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.
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 () // Delete characters
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 '\ 0 '. C_str () returns an array of characters ending with '\ 0', while copy () copies or writes the content of the string to an existing c_string or character array. The C ++ string does not end with '\ 0. 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
A c ++ character string has three types of sizes: a) the number of existing characters. The functions are size () and length (), which 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. If it is not enough, the system will throw the length_error exception c) Capacity () the maximum number of characters that the 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 its parameters,
The default value is 0. In this case, the string is not forcibly reduced.
It is also necessary to repeat the questions about conversion between C ++ strings and C strings. Many people may encounter such problems, your own program needs to call others' functions and classes (such as database connection function connect (char *, char *)), however, others' function parameters are in the char * format. We know that the character arrays returned by c_str () and data () are owned by this string, therefore, it is a const char *. to be used as a parameter of the function mentioned above, you must copy it to a char *. Our principle is that it is not used without using a C string. 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 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 open 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 [] operator of const string a; is still valid for the index value of A. Length (), and the return value is '\ 0 '. 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 '\ 0'
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.
2.4 comparison functions
C ++ strings support common comparison operators (>,>=, <,<=, == ,! =), Or even comparison between string and C-string (for example, STR <"Hello "). When using the>, >=, <, <= operators, the characters are compared alphabetically according to the "current character characteristics. 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 ''\ 0' 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 ');
S. push_back ('A'); // This function can only add a single character to understand STL easily.
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 );
The insert () function in this form 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 overload 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 refers to 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
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
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 )).
The second part is about the support of C ++ strings for the iterator. I will write it as needed (that is, if you don't need it, I am happy, haha ...).
Okay, I 've probably elaborated on the string type, hoping to play a leading role, this gives beginners an understanding of string without having to begin to face complicated internal structures and numerous precautions. There are many reference books on strings in more detail. In fact, my content is also obtained from the C ++ standard library, and I add a few comments of my own, therefore, I would like to thank the authors and translators of this book. Anyone who cited this article should indicate that the author is Nicola M. josutis and the translator is Hou Jie/Meng Yan. Don't mention me, though. Errors in any opinion have nothing to do with me (except a few words that reflect my subjective thoughts here, that is, those words ).