String usage summary in c ++

Source: Internet
Author: User

The reason why the char * string is discarded and the string class in the C ++ standard library is used is because it is not necessary to compare it with the former.
Worried about whether the memory is sufficient, the length of the string, and so on, and as a class, the integrated operation function is sufficient to meet our needs in most cases (or even 100%. We can use = to assign values, =
Compare, + concatenate (isn't it easy ?). We can think of it as the basic data type of C ++.

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 "beginning with stridx" in the str string as the initial value of the string.
D) string s (str, stridx, strlen) // take the part of the string str that "starts 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
C
The C_string method provided by ++ 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 ()
This size refers to the maximum number of characters that can be contained in the current C ++ string. It may be related to the limitation of the machine or the size of the 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, it will throw the length_error exception c) capacity () before the memory is reassigned
The maximum number of characters that a string can contain. 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 C ++ string and C String Conversion questions.
Many people will encounter such problems. Their own programs need to call others' functions and classes (such as database connection function Connect (char *, char *)), but other functions
The number is in the char * format, and 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, you must copy it to a char *. Our principle is that the C string is not used. In this case, our processing method is: if
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
Those who still use the C string for programming now (say they are not a good guy at all, maybe they started programming when we were still wearing slashes, haha ...) All the written functions are standard.
We don't have to perform a 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. And at () will check, if you use
If the index is invalid at (), an out_of_range exception is thrown.
One exception is that const string
The operator [] of 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 (>,>=, <,<=, == ,! =), And even supports the comparison of string and C-string (for example
Str <"hello "). When using the operators>, >=, <, <=, and <=, the characters are obtained in alphabetical order based on the "current character feature ".
Comparison. 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 value can be a string (for example, s = ns)
, 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 feel sick, you have to continue reading the following:
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
The form of inserting characters using the iterator 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.

Most
Then 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 )).
Author: THISISPAN

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.