std::string detailed

Source: Internet
Author: User
Tags logical operators strlen traits

Link: http://blog.csdn.net/debugconsole/article/details/8677313

The reason to discard char* strings and select the String class in the C + + standard library is because he compares with the former, doesn't have to worry about enough memory, string length, and so on, and as a class, his integrated operations function is enough to do most of our (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 Standard Template Library (STL) provides a std::string class that is a std::basic_string of a container class that uses strings as normal types and supports comparisons, joins, traversal, STL algorithms, replication, assignment, and so on, which are defined in <string> header file.

#include <string>/Note this is not string.h string.h is a C string header file
1. Declaring a C + + string
Constructors for std::string classes

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 constructor generates a copy of STR string (const string& 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 (const string& str, size_type Pos,strlen)//Set the initial value of the string in the portion of the string str "beginning with POS and at most strlen"
e) string s (const char *s)//The C string as the initial value of s
f) string s (const char* CStr, Size_type N)//initializes the initial value as string s using the first n characters of String str.
g) string s (int Num,char 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.

Length_error exception is thrown when the constructed string is too long to be expressed


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 (int nstart,int nend)//delete Nstart-nend position 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 that corresponds to a C + + string by using 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 ', while 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
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 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 if it's not enough, it throws a 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 has to say that const string A; the operator [] is still valid for the index value of 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 '
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.


iterate through all the characters, which can be done by the C-style index or STL iterations (using const_iterator if no modification is required).

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
The C + + string supports the common comparison operator (>,>=,<,<=,==,!=) and even supports a comparison of string and 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 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 ');
2.5.1, inserts other elements at the end of the string.
S.push_back (' a ');//This function can only add a single character to the STL familiar understanding is simple
2.5.2, inserts a string or character at the specified location.

You may 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. There are several forms of the
Delete function erase () (really annoying.) ), there are also several replacement functions replace (). For example:
string s= "il8n";
S.replace (1,2, "nternationalizatio"), and/or 2 from index 1 to back c_string

2.5.3, deletes a part of the 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

Lookup function for std::string class
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 (e.g. if (S.find ("jia") = = String::npos).

3.1. Using STL algorithm

std::string name = "Marius";

Make a string all 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 string

Std::reverse (Name.begin (), Name.end ());

BOOL Iswhitespace (char ch)

{

return ch = = ' ' | | ch = = ' t ' | | ch = = ' V ' | |

ch = = ' R ' | | ch = = ' n ';

}

std::string name = "Marius";

Remove white space characters

Std::string::iterator newend = std::remove_if (Name.begin (), Name.end (), iswhitespace);

Name.erase (Newend);

 

substitution function for std::string class

Function 1:
Std::string & Replace (Size_type pos1, size_type N1, const std::string & str, size_type pos2 = 0, size_type n2 = NP OS);

Function: Replaces the N1 character at the beginning of the current string from the POS1 position by using the N2 character starting at the position pos2 with the STR string.
It can be understood that the function deletes the current string from the N1 character starting at POS1, and then fills the current string with the entire str string or the N2 character starting with Str from POS2, starting at the POS1 position.

Reminder: If the value of the N1 or N2 exceeds the length of the corresponding string, the actual length is the same, and the access bounds will not occur.

Attention:
A, if the location specified by pos1 exceeds the current string range, throwing Std::out_of_range exception, not capturing will cause coredump.
b, if the location specified by Pos2 exceeds the range of the replacement string str, throwing a Std::out_of_range exception and not capturing will result in Coredump.

Function 2:
std::string& Replace (size_type POS, size_type N1, const char * s, size_type n2);

Function: Replaces the N1 character at the beginning of the POS position with the first N2 character of the string S.
It can be understood that the function deletes the current string from the N1 character at the beginning of the POS and then fills in the current string with the first N2 character of the string S. Similar to the pos2 of function 1 equals 0, you must specify this case for N2, but there is a difference, and the following note describes the difference.
Attention:
A, if the position specified by the POS exceeds the current string range, throwing a Std::out_of_range exception and not capturing will cause coredump.
B, the function does not judge the size relationship between the string s and the N2, and it strictly copies N2 characters from the beginning of s to the specified position. If N2 represents a length that is beyond s, it reads the memory space behind S and may be coredump by the memory access bounds. However, the N2 of function 1 can be out of range, whichever is the actual length.

Function 3:
std::string& Replace (size_type POS, size_type N1, const char* s);

Function: Replaces the N1 character at the beginning of the POS position with the string s ending with '.
It can be understood that the function deletes the current string from the N1 character at the beginning of the POS and then fills the current string with the string s from start to all characters ending with ' '.

Note: If the POS-specified position exceeds the current string range, throwing a Std::out_of_range exception, not capturing will result in Coredump.

Function 4:
std::string& Replace (size_type POS, Size_type N1, Size_type N2, Char c);

The function: replaces the N1 character at the beginning of the POS position with the character that is represented by N2 C.
It's understandable: the function deletes the current string from the N1 character at the beginning of the POS and then fills the current string with the N2 C character, starting at the POS position.

Note: If the POS-specified position exceeds the current string range, throwing a Std::out_of_range exception, not capturing will result in Coredump.

Function 5:
std::string& replace (iterator I1, iterator i2, const std::string& str);

Function: Replaces the character between the current string [i1,i2) with string str.

Function 6:
std::string& replace (iterator I1, iterator I2, const char* S, Size_type N);

The function: replaces the character between the current string [I1,i2) with the first n characters of the string s.

Function 7:
std::string& replace (iterator I1, iterator I2, const char* s);

Function: Replaces the character between the current string [I1,i2) with the string s ending with '.

Function 8:
std::string& replace (iterator I1, iterator I2, Size_type N, char c);

The function: replaces the characters between the current string [I1,i2) with the characters represented by N C.

internal type definition for std::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:: Reverse_iterator reverse_iterator; typedef:: Reverse_iterator const_reverse_iterator; static const Size_type NPOs = static_cast (-1);

assignment operators for std::string classes

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);

logical operators for std::string classes

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 ');

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.