Usage of (c + +) string

Source: Internet
Author: User

(Transferred from Http://www.cnblogs.com/yxnchinahlj/archive/2011/02/12/1952550.html)

The reason for discarding the char* string is to choose the string class in the C + + standard library because he does not have to worry about the adequacy of the memory, the length of the string, and so on, and as a class, his integrated operation function is sufficient to fulfill the needs of most of our cases (even 100%). We can use = To do the assignment, = = to compare, + do concatenation (is not very simple?). We can do it as a basic data type for C + +.

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

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 of string is used directly, and the function is to initialize STR to an empty string.

The constructor and destructor for the string class are as follows:
a) string s; Generates an empty string s
b) string S (str)//Copy constructor generates a copy of STR
c) string s (STR,STRIDX)//The part of "starting at position Stridx" within the string str as the initial value of the string
d) string s (Str,stridx,strlen)//The part of the string str "starting at STRIDX and at most strlen" as the initial value of the string
e) string s (CStr)//C string as the initial value of s
f) string S (Chars,chars_len)//The first chars_len character of the C string as the initial value of the string s.
g) string S (num,c)//Generate a string containing num characters c
h) string S (beg,end)//The initial value of the string s as a character in the interval beg;end (not including the end)
i) s.~string ()//Destroy all characters, free memory
It's all very simple, and I won't explain it.

2. String manipulation functions
Here is the focus of the C + + string, I first put the various operational functions listed, do not like to see all the functions of the people can find their favorite functions, and then to see his detailed explanation.
A) =,assign ()//Assign new value
b) Swap ()//Exchange two strings of content
c) +=,append (), push_back ()//Add characters at the tail
d) Insert ()//Insert character
e) Erase ()//delete character
f) Clear ()//delete all characters
g) Replace ()//Replace character
h) +//concatenation string
i) ==,!=,<,<=,>,>=,compare ()//Compare strings
j) Size (), Length ()//number of characters returned
k) max_size ()//The maximum possible number of characters returned
L) empty ()//Determine if the string is empty
m) Capacity ()//return the character capacity before reallocation
N) reserve ()//retain a certain amount of memory to accommodate a certain number of characters
o) [], at ()//Access single character
p) >>,getline ()//read a value from stream
Q) <<//write value to stream
r) Copy ()//Assign a value to a c_string
s) c_str ()//return content as C_string
T) data ()//returns the content as a character array
u) substr ()//return a substring
V) Find function
W) begin () end ()//provide an STL-like iterator support
x) Rbegin () rend ()//Reverse iterator
Y) Get_allocator ()//Return Configurator
Here is a detailed description:

2. 1 conversion of C + + strings and C strings
C + + provides a way to get the corresponding c_string from a C + + string by using data (), C_str (), and copy (), where data () returns the string contents as an array of characters, but does not add '% '. C_STR () returns an array of characters ending with ' s ', while copy () copies or writes the contents of the string to an existing c_string or character array. The C + + string does not end with '/'. My advice is to use C + + strings in the program, unless you have to choose C_string. Since it is just a brief introduction, detailed introduction brushing, who would like to further understand the use of the precautions can give me a message (to my inbox). I'll explain in detail.

2. 2 size and capacity functions
There are three sizes of a C + + string:

A) The existing number of characters, the function is size () and length (), they are equivalent. Empty () is used to check if the string is empty.

b) max_size ()
This size refers to the number of characters that the current C + + string can contain, which is likely to be related to the limitations of the machine itself or the size of contiguous memory where the string is located. We generally do not care about him, should be large enough for us to use. But not enough, will throw Length_error exception c) capacity () before reallocating memory
The maximum number of characters that string can contain. Another point to note here is the reserve () function, which re-allocates memory for string. The size of the reallocation is determined by its parameters, and the default parameter is 0, which is a non-mandatory reduction of string.

It is also necessary to repeat the C + + string and C string conversion problems, many people will encounter such a problem, their own programs to invoke other people's functions, classes and so on (such as database connection function connect (char*,char*)), but the function parameters of others are in the form of char*, And we know that the character array returned by C_STR (), data () is owned by the string, so it is a const char* that, as a parameter to the function mentioned above, must also be copied to a char*, and our principle is not to use the C string. So, the way we handle this is if this function does not modify the contents of the parameter (that is, char*), we can connect ((char*) Userid.c_str (), (char*) passwd.c_str ()), But this time is dangerous, because the converted string can actually be modified (interested can try it yourself), so I emphasize that unless the function is called when the parameters are not modified, it must be copied to a char* up. Of course, the more secure way is to copy to a char* whatever the situation. At the same time, we also pray that we still use C strings to program the experts (said they are a master not a bit too, perhaps when we still wear diaper when they began programming, haha ... The functions written are more canonical, so we don't have to cast them.

2. 3 element Access
We can use the subscript operator [] and the 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 ()), and if the index fails, it causes undefined behavior. The at () checks if the index is invalid when using at () and throws an Out_of_range exception.
One exception has to be said, const string A; the operator [] is still valid for the index value a.length (), and its return value is ' + '. 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 do not approve of a reference or pointer assignment similar to the following:
char& r=s[2];
char* p= &s[3];
As soon as redistribution occurs, the r,p immediately expires. The way to avoid this is to not use it.

2. 4 comparison function
The C + + string supports common comparison operators (>,>=,<,<=,==,!=) and even supports string comparisons with c-string (such as str< "Hello").

When using the >,>=,<,<= operators, the characters are compared in dictionary order according to the current character attribute. Dictionaries are smaller than the previous characters, and the order of comparison is compared from front to back, and the size of the two strings is determined by the comparison of the two characters in this position by encountering unequal characters. Also, string ("AAAA") <string (AAAAA).
Another powerful comparison function is the member function compare (). He supports multi-parameter processing and supports comparisons with index values and length-locating substrings. He returns an integer to indicate the result of the comparison, meaning the return value is as follows: 0-equal 〉0-greater than <0-less than. Examples are as follows:
String S ("ABCD");

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

S.compare (s); Equal
S.compare (0,2,s,2,2); Compare less than 0 with "AB" and "CD"
S.compare ("Bcx", 2); Compare with "BC" and "BC".
What do you think? Work can be full of it! What the? Not enough to satisfy your appetite? Well, wait, there's a more personal comparison algorithm behind it. Give a hint first, using the STL's comparison algorithm. What the? Do you have a very ignorant stl? Come on, you've rebuilt it!

2. 5 Changing content
This takes up a large part of the operation of the string.

The first assignment, of course, is to use the operator =, the new value can be a string (for example: S=ns), c_string (such as: s= "Gaint") or even a single character (e.g. s= ' J '). You can also use the member function assign (), a member function that gives you more flexibility in assigning a value to a string. Or an example:

S.assign (str); Don't say
S.assign (str,1,3);//If STR is "Iamangel", it is to assign "AMA" to the string
S.assign (Str,2,string::npos);//Assign the string str from the index value 2 to the end to the S
S.assign ("Gaint"); Don't say
S.assign ("Nico", 5);//Assign the ' n ' I ' C ' o ' to the string
S.assign (5, ' X ');//assign five x to a string
There are three ways to empty a string: s= ""; S.clear (); S.erase ();(I feel more and more like an example than speaking to make others easy to understand! )。
String provides a number of functions for inserting (insert), deleting (erase), replacing (replace), and adding characters.
First, add the character (the increase here is on the tail), the function has + =, append (), push_back (). Examples are as follows:
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,1,3)//does not explain the interpretation of the assign of the function arguments with the preceding
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 STL familiarity is easy to understand

Perhaps you need to insert a string somewhere in the middle of the string, and you can use the Insert () function, which requires you to specify an index of the placement, and the inserted string will be placed behind the index.

S.insert (0, "my Name");
S.insert (1,STR);
This form of the insert () function does not support passing in a single character, where a single character must be written as a string (disgusting). Now that you feel nauseous, you have to read the following passage: 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,char c) and insert ( Iterator Pos,size_type Num,char c). Where Size_type is an unsigned integer, iterator is char*, so you can't do this by calling the Insert function: Insert (0,1, ' j '); What is the first parameter to convert to? So you have to write this: insert ((string::size_type) 0,1, ' J ')! The second form points out the form of inserting characters using iterators, which is mentioned later. By the way, string has a lot of operations that use STL's iterators, and he tries to do the same with STL.
There are several ways to delete a function erase () (it's annoying!). ), replacing the function replace () also has several. For example:
String s= "il8n";
S.replace ("Nternationalizatio");//Replace with the following c_string from the 2 that start at index 1
S.erase (13);//delete all from index 13
S.erase (7,5);//delete 5 from the beginning of index 7

2. 6 extracting substrings and string connections
The function of the substring is: substr (), in the following form:
S.substr ();//Returns the entire contents of s
S.SUBSTR (11);//Sub-string from index 11
S.substr (5,6);//6 characters starting from index 5
The function that combines two strings is +. (Who does not understand please call 120)

2. 7 input/output operation
1. >> reads a string from the input stream.
2. << writes a string to the output stream.
Another function is Getline (), which reads a line of content from the input stream until it encounters a break or ends at the end of the file.

2. 8 Search and find
There are a lot of 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 within the character range that matches the search criteria, and return NPOs without locating the target. The parameters of all functions are described as follows:
The first parameter is the object being searched. The second parameter (optional) indicates the search starting index within the string, and the third parameter (optional) indicates the number of characters searched. Relatively simple, not much to say that do not understand can be presented to me, I will answer carefully. Of course, a more powerful STL search will be mentioned later.
?
Finally say NPOs meaning, the type of String::npos is String::size_type, so, once you need to compare an index with NPOs, this index value must be string::size) type, more cases, We can directly compare the function with the NPOs (e.g., if (S.find ("jia") = = String::npos).

Usage of (c + +) string

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.