C + + String type detailed __c++

Source: Internet
Author: User

From:http://citycowboy.blog.sohu.com/50058804.html

The string class in the C + + standard library is used to discard char* strings. Because he compares with the former, does not have to worry about memory enough, string length, and so on, and as a generic class appears, he integrates the operation function enough to complete our most (even 100%) needs. We can use = for assignment operation, = = For comparison, + do series (is not very simple?). We can think of it as the basic data type of C + +.

The definition of Strinig in C + + is: typedef basic_string<char> string; That is, the string class in C + + is a generic class, and a standard class instantiated by a template is inherently not a standard data type.

OK, get to the point ...
First, in order to use the string type in our program, we must include the header file <string>. As follows:
#include <string>/Note this is not string.h string.h is a C string header file

using namespace Std; This statement is essential, otherwise some compilers will not recognize

1. Declaring a C + + string
Declaring a string variable is simple:
String Str;
So we declare a string variable, but since it is a class, there are constructors and destructors. The above declaration does not pass in parameters, so the default constructor for string is used directly, and this function is to initialize STR to an empty string. The constructors and destructors for the string class are as follows:
a) string s; Generate an empty string s
b) string S (str)//Copy constructors generate a replica of STR
c) string s (str,stridx)//Stridx the part of the string str "beginning with position" as the initial value of the string
d) string s (str,stridx,strlen)//Stridx the part of the string str "beginning with the length of strlen" as the initial value of the string
e) string s (CStr)//The C string as the initial value of s
f) string S (chars,chars_len)//Chars_len The first character of the C string as the initial value of the string s.
g) string S (num,c)//Generate a string containing num C characters
h) string S (beg,end)//The initial value of the string s as a character in the interval beg;end (not including end)
i) s.~string ()//Destroy all characters, free memory
It's simple, I don't explain it.
2. String manipulation functions
Here is the focus of C + + string, I first listed a variety of operating functions, do not like to read all the functions of the person can find their favorite function, and then to see his detailed explanation.
A) =,assign ()//Assign a new value
b) Swap ()//Exchange two-string contents
c) +=,append (), push_back ()///Add character at tail
D insert ()//Insert character
e) Erase ()///delete character
f) Clear ()//Remove all characters
g) Replace ()//Replace character
h) +//concatenated string
i) ==,!=,<,<=,>,>=,compare ()//comparison string
j) Size (), Length ()//return number of characters
k) max_size ()//returns the possible maximum number of characters
L) empty ()//To determine whether the string is empty
m) Capacity ()//returns the character capacity before redistribution
N) reserve ()//reserve a certain amount of memory to accommodate a certain number of characters
o) [], at ()//Access single character
p) >>,getline ()//reading a value from stream
Q <<//To write the value of the profit stream
r) Copy ()//Assign a value to a c_string
s) c_str ()//return content to C_string
T) data ()//returns the content as a character array
u) substr ()//Return of a substring
V) Lookup function
W) begin () end ()//provide iterator support similar to STL
x) Rbegin () rend ()//Reverse iterators
Y) Get_allocator ()//Return Configurator
Here is a detailed description:
2. 1 C + + string and C-string conversions
C + + provides a c_string method for C + + strings that uses data (), C_str (), and copy (), where data () returns the contents of the string as a character array, but does not add '. C_STR () returns an array of characters that end with ', ' and copy () copies or writes the contents of the string to an existing c_string or character array. C + + strings do not end With ' ". My advice is to use C + + strings in your program, unless you have to choose C_string. As just a brief introduction, detailed introduction skimming, who would like to learn more about using the notes can give me a message (to my inbox). I explained in detail.
2. 2 size and capacity functions
A C + + string exists in three sizes: a) The existing number of characters, the function is size () and length (), and they are equivalent. Empty () is used to check whether the string is empty. b max_size () This size refers to the maximum number of characters that can be contained in the current C + + string, possibly in relation to the machine itself or the size of contiguous memory at the location of the string. We usually do not care about him, should be large enough for us to use. But not enough, it throws Length_error exception C) capacity () the maximum number of characters a string can contain before the memory is reassigned. Another point to note here is the reserve () function, which allocates memory for string. The size of the reassignment is determined by its parameters, and the default parameter is 0, which makes a non-mandatory reduction to string.

It is also necessary to repeat the problem of C + + string and C string conversion, many people will encounter such a problem, their own program to invoke other people's functions, classes and things (such as database connection function connect (char*,char*)), but other people's function parameters are char* form, And we know that the character array returned by C_STR (), data () is owned by the string, so it is a const char* and must be copied to a char* as an argument to the function mentioned above, and our principle is not to use a C string. So, the way we handle this is this: if this function does not modify the contents of the parameter (i.e. char*), we can connect ((char*) Userid.c_str (), (char*) passwd.c_str ()), But there is a danger at this point, because the converted string can actually be modified (you can try it yourself), so I emphasize that unless the function is called without modifying the parameters, it must be copied to a char*. The safer way, of course, is to copy everything to a char*. At the same time we also pray that we still use the C string to program the masters (say they are a master is not too far, perhaps when we still wear pants, they began to program, haha ... ) write functions that are relatively canonical so that we do not have to cast them.

2. 3 element Access
We can use the subscript operator [] and function at () to access the characters contained by the element. However, it should be noted that the operator [] does not check whether the index is valid (valid index 0~str.length ()), and if the index fails, it can cause undefined behavior. at () checks that if the index is invalid when you use at (), a Out_of_range exception is thrown.
One exception to this is that const string A; the operator [] is still valid for the index value of A.length (), and its return value is ' yes '. In all other cases, the A.length () index is invalid. Examples are as follows:
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 ' to '
Str.at (Str.length ());//throw Out_of_range
Cstr.at (Cstr.length ())////throw Out_of_range

I don't approve of a reference or pointer assignment similar to the following:
char& r=s[2];
char* p= &s[3];
Because once the redistribution occurs, the r,p immediately expires. The way to avoid it is to not use it.

2. 4 comparison functions
C + + strings support common comparison operators (>,>=,<,<=,==,!=) and even string comparisons with c-string (such as str< "Hello"). When using >,>=,<,<= these operators are compared according to the "current character attribute" by the dictionary order of the characters. The dictionary is sorted by a small character, the order of comparison is a backward comparison, and the unequal character is encountered to determine the size of two strings by comparing the two characters in that position. At the same time, string ("AAAA") <string (AAAAA).
Another powerful comparison function is the member function compare (). He supports multi-parameter processing, which enables comparisons using index values and lengths to locate substrings. He returns an integer to indicate the comparison, and the return value is as follows: 0-equal 〉0-greater than <0-. Examples are as follows:
String S ("ABCD");

S.compare ("ABCD"); return 0
S.compare ("DCBA"); Returns a value less than 0
S.compare ("AB"); Returns a value greater than 0

S.compare (s); Equal
S.compare (0,2,s,2,2); Compare "AB" with "CD" for less than 0
S.compare (1,2, "bcx", 2); Compare "BC" and "BC".
What do you think. The work can be all right. What the. It's not enough to satisfy your appetite. Well, wait, there's a more personalized comparison algorithm behind it. First give a hint, using the STL comparison algorithm. What the. The STL is a Greek. Come on, you have to rebuild.

2. 5 Change Content
This accounts for a large portion of the operation of strings.
The first assignment, of course, is to use the operator = The new value can be a string (such as: S=ns), c_string (such as: s= "Gaint") or even a single character (such as: S= ' J '). You can also use the member function assign (), which allows you to more flexibly assign a value to a string. Let me give you an example:
S.assign (str); Don't say
S.assign (str,1,3)//If STR is "Iamangel" is to assign "AMA" to the string
S.assign (Str,2,string::npos)//String str from index value 2 to end assigned to S
S.assign ("Gaint"); Don't say
S.assign ("Nico", 5);//assign ' n ' I ' C ' o ' to the string
S.assign (5, ' X ');//Assign five X to string
There are three ways to empty a string: s= ""; S.clear (); S.erase ();(I'm getting more and more comfortable with examples than talking to others. )。
String provides a number of functions for inserting (insert), deleting (erase), replacing (replace), and adding characters.
First of all, add the character (this is said to increase on the tail), the function has + =, append (), push_back (). Examples are as follows:
s+=str;//plus a string
s+= "My name is JIAYP";//Add a C string
s+= ' a ';//Add a character

S.append (str);
S.append (str,1,3)//does not explain the same previous function parameter assign
S.append (Str,2,string::npos)//no explanation.

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 the STL familiar understanding is simple

Maybe you need to insert a string somewhere in the middle of the strings, at which point you can use the Insert () function, which requires you to specify an index of placement, and the inserted string will be placed behind the index.
S.insert (0, "my Name");
S.insert (1,STR);
This form of insert () function does not support passing in a single character, at which point a single character must be written in a string form (disgusting). Now that you feel nauseous, you have to read the following paragraph: To insert a single character, the Insert () function provides two overloaded functions for inserting a single character operation: Insert (Size_type index,size_type num,chart c) and insert (iterator Pos,size_type Num,chart c). Where Size_type is an unsigned integer, iterator is char*, so it is not OK for you to invoke the Insert function: Insert (0,1, ' J '), which is the first argument to be converted to. So you have to write this: insert ((string::size_type) 0,1, ' J '). The second form points to the use of the iterator placement character, which is mentioned later. By the way, string has many operations that use STL iterators, and he tries to be as close to the STL as possible.
Delete function erase () There are also several kinds of forms (I'm annoying. ), there are also several replacement functions replace (). For example:
String s= "il8n";
S.replace (1,2, "nternationalizatio");//replace 2 from index 1 to back c_string
S.erase (13);//Remove all from index 13
S.erase (7,5)//delete 5 from index 7

2. 6 extracting substring and string concatenation

The function of the caption substring is: substr (), in the form as follows:
S.SUBSTR ()//return all contents of S
S.SUBSTR (11);//Sub string from index 11
S.SUBSTR (5,6)//starting from index 5 6 characters
The function of combining two strings is +. (who don't understand, please call 120)

2. 7 Input and output operations
1. >> reads a string from the input stream.
2. << writes a string to the output stream.
Another function is Getline (), which reads a row from the input stream until it encounters a line break or to the end of the file.

2. 8 Search and find
There are a lot of lookup functions and powerful features, 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 within the character range that matches the search criteria, and return NPOs if no target is found. The parameters of all functions are described below:
The first parameter is the object being searched. The second parameter (optional) indicates the search start index within the string, and the third parameter (optional) indicates the number of characters searched. Relatively simple, not much to say not understand can be presented to me, I will answer carefully. Of course, a more powerful STL search will be mentioned later.
Last but not the NPOs, the String::npos type is string::size_type, so once you need to compare an index to NPOs, the index value must be string::size) type, and more often, We can compare functions directly to NPOs (such as: if (S.find ("Jia") ==string::npos).
The second part is about C + + string to the iterator support, depending on the needs of everyone I will write out (meaning is not need to even, I am happy to be happy, haha ...) )。
All right, it's about the string type, and hopefully it's a good idea to give beginners an understanding of string without having to start with complex internal structures and countless caveats. A more detailed description of the string there are many reference books, in fact, my content is also from the C + + standard library, plus a few of their own views, so to thank the book's author and translator. Anyone who references this article should indicate that the author is Nicolai M.josuttis translator is Houtie/Meng. But do not mention me, and any errors of opinion have nothing to do with me (except for a few words that reflect my subjective thoughts here, as well as those words).

String Function List

The name of the function Describe
Begin Gets the iterator that points to the beginning of the string
End Gets the iterator that points to the end of the string
Rbegin Iterator that points to the beginning of the reverse string
Rend Gets the iterator that points to the end of the reverse string
Size Get the size of the string
Length Same function as size function
Max_size Possible maximum size of string
Capacity The possible size of the string without reallocating memory
Empty To determine if it is empty
Operator[] Take the first few elements, the equivalent of an array
C_str Get a C-style const char* string
Data Get string content Address
Operator= Assignment operator
Reserve Reserve space
Swap Swap functions
Insert Insert character
Append Append characters
Push_back Append characters
operator+= + = operator
Erase Delete string
Clear Empty all content in a character container
Resize Reallocate Space
Assign The same as the assignment operator
Replace Alternative
Copy String to Space
Find Find
RFind Reverse Lookup
Find_first_of Finds any character in a substring, returns the first position
Find_first_not_of Finds any character that does not contain a substring, returns the first position
Find_last_of Finds any character in a substring, returns the last position
Find_last_not_of Finds any character that does not contain a substring, returns the last position
Substr Get string
Compare Comparing strings
operator+ String links
operator== Judge whether the equality
operator!= Whether the judge is not equal to
operator< Determine if less than
Operator>> Reading a string from the input stream
operator<< String writes to output stream
Getline Read a row from the input stream
Related Article

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.