One of the STL: a string usage explanation

Source: Internet
Author: User

Reproduced in: http://blog.csdn.net/longshengguoji/article/details/8539471

A string is one of the most complex aspects of programming. The STL String class provides a powerful feature that allows a lot of tedious programming content to be done with simple statements. The string string class reduces the three most common and most damaging errors in C programming: exceeding array boundaries, accessing array elements by violating a pointer that is initialized or assigned an error value, and retaining a "hanging" pointer after releasing an array of previously allocated storage units.

List of String functions

Name of function Describe
Begin Get the iterator that point to the beginning of the string
End Get the iterator that points to the end of the string
Rbegin Get the iterator that point 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 The maximum possible size of a string
Capacity The possible size of a string without reallocating memory
Empty Determines whether the empty
Operator[] Take the first few elements, which are equivalent to the array
C_str Get the C-style const char* string
Data Get string content Address
Operator= Assignment operator
Reserve Reserved space
Swap Swap functions
Insert Insert character
Append Append character
Push_back Append character
operator+= + = operator
Erase Delete a string
Clear Empty all contents of the character container
Resize Reassign Space
Assign Same as the assignment operator
Replace Alternative
Copy String to Space
Find Find
RFind Reverse Lookup
Find_first_of Finds any character in the containing substring and returns to the first position
Find_first_not_of Find any characters that do not contain substrings, return to the first position
Find_last_of Finds any character in the containing substring and returns to the last position
Find_last_not_of Find any characters that do not contain substrings, and return to the last position
Substr Get string
Compare Comparing strings
operator+ String links
operator== Judging if they are equal
operator!= Judging if not equal to
Operator<</span> Judging if it is less than
Operator>> Reads a string from the input stream
operator<< String writes to the output stream
Getline Reads a line from the input stream

6 Find functions are overloaded 4 times, the following is an example of the Find_first_of function to illustrate their arguments, the other functions and their parameters, that is, a total of 24 functions:

Size_type find_first_of (const basic_string& s, size_type pos = 0)
Size_type find_first_of (const chart* S, size_type pos, Size_type N)
Size_type find_first_of (const chart* s, size_type pos = 0)
Size_type find_first_of (CharT c, size_type pos = 0)

All lookup functions return a size_type type, which is typically the location of the string found and returns String::npos if not found.
It is important to note that all comparisons with String::npos must be used with string::size_type, not directly using int or unsigned int. In fact, String::npos represents-1.

Constructor for String class

String (const char *s); Initialize with C string s
string (int N,char c); Initialize with n characters c
In addition, the string class supports both the default constructor and the copy constructor, such as String s1;string s2= "Hello", which is the correct notation. A Length_error exception is thrown when a constructed string is too long to be expressed

Character manipulation of the string class
const char &operator[] (int n) const;
const char &at (int n) const;
Char &operator[] (int n);
char &at (int n);
Operator[] and at () both return the position of the nth character in the current string, but the at function provides a scope check that throws a Out_of_range exception when it crosses the border, and the subscript operator [] does not provide check access.
const char *data () const;//returns a non-null-terminated C-character array
const char *C_STR () const;//returns a null-terminated C string
int copy (char *s, int n, int pos = 0) const;//copies the n characters starting at Pos in the current string to a character array starting with S, returning the number of actual copies

Property Description of String

int capacity () const; Returns the current capacity (that is, the number of elements in a string that do not have to increase memory)
int max_size () const; Returns the length of the largest string that can be stored in a string object
int size () const; Returns the size of the current string
int length () const; Returns the length of the current string
BOOL empty () const; Whether the current string is empty
void Resize (int len,char c);//Set the current size of the string to Len and fill in the insufficient part with the character C

Input and output of the string class

The string class overloaded operator operator>> is used for input, and the same overloaded operator operator<< is used for output operations.
The function getline (IStream &in,string &s) is used to read the string from the input stream in to s, separated by a newline character ' \ n '.

Assignment of String

String &operator= (const string &s);//assigns the string s to the current string
String &assign (const char *s);//Assigning a value with the C type string s
String &assign (const char *s,int n);//n characters assigned value starting with C string s
String &assign (const string &s);//assigns the string s to the current string
String &assign (int n,char c);//assigns a value to the current string with n characters c
String &assign (const string &s,int start,int N);//assigned the current string from the n characters in the string s from start
String &assign (Const_iterator first,const_itertor last);//Assigning the part between first and last iterators to a string

Connection to String

String &operator+= (const string &s);//Connect the string s to the end of the current string
String &append (const char *s); Concatenate the C-type string s to the end of the current string
String &append (const char *s,int N),//The first n characters of type C string s connect prompt to the end of the current string
String &append (const string &s); With operator+= ()
String &append (const string &s,int pos,int N);//n characters starting from Pos in string s connect prompt to the end of the current string
String &append (int n,char c); Adds n characters to the end of the current string C
String &append (Const_iterator first,const_iterator last);//Connect the part between the iterator first and last to the end of the current string

Comparison of String

BOOL operator== (const string &s1,const string &s2) const;//compares two strings for equality
The operators ">", "<", ">=", "<=", "! =" are overloaded for string comparisons;
int compare (const string &s) const;//Compare the size of the current string and s
int compare (int pos, int n,const string &s) const;//compares the current string with the size of S of N characters starting from Pos
int compare (int pos, int n,const string &s,int pos2,int n2) const;// Compares the size of a string of n characters starting at the beginning of the current string from Pos with N2 characters starting with Pos2 in S
int compare (const char *s) const;
int compare (int pos, int n,const char *s) const;
int compare (int pos, int n,const char *s, int pos2) const;
The Compare function returns -1,== when > returns 1,< when return is 0

Substring of string
String substr (int pos = 0,int n = NPOs) const;//Returns a string of n characters starting at Pos

Exchange of String:
void Swap (string &s2); Swap the current string with the value of S2


Find function for string
int find (char c, int pos = 0) const;//The position of the character C at the current string starting from the POS
int find (const char *s, int pos = 0) const;//Find the position of the string s in the current string starting from the POS
int find (const char *s, int pos, int n) const;//from Pos to find the position of the first n characters in the string s in the current string
int find (const string &s, int pos = 0) const;//Find the position of the string s in the current string starting from the POS
Returns the location when the lookup succeeds, and fails to return the value of String::npos
int RFind (char c, int pos = NPOs) const;//The position of the character C in the current string from the beginning of the POS
int rfind (const char *s, int pos = NPOs) const;
int rfind (const char *s, int pos, int n = npos) const;
int RFind (const string &s,int pos = NPOs) const;
Finds the position of the first n characters in the string s in the current string from the beginning of the POS, and returns the value of String::npos on failure.
int find_first_of (char c, int pos = 0) const;//Find the first occurrence of character C from Pos
int find_first_of (const char *s, int pos = 0) const;
int find_first_of (const char *s, int pos, int n) const;
int find_first_of (const string &s,int pos = 0) const;
Finds the position of the character in the first n-character array of s in the current string starting from Pos. Find failed return String::npos
int find_first_not_of (char c, int pos = 0) const;
int find_first_not_of (const char *s, int pos = 0) const;
int find_first_not_of (const char *s, int pos,int n) const;
int find_first_not_of (const string &s,int pos = 0) const;
Finds the first occurrence of a character not in the string s from the current string, fails back to String::npos
int find_last_of (char c, int pos = NPOs) const;
int find_last_of (const char *s, int pos = NPOs) const;
int find_last_of (const char *s, int pos, int n = npos) const;
int find_last_of (const string &s,int pos = NPOs) const;
int find_last_not_of (char c, int pos = NPOs) const;
int find_last_not_of (const char *s, int pos = NPOs) const;
int find_last_not_of (const char *s, int pos, int n) const;
int find_last_not_of (const string &s,int pos = NPOs) const;
Find_last_of and find_last_not_of are similar to find_first_of and find_first_not_of, except that they look forward from behind.


substitution function for string
String &replace (int p0, int n0,const char *s);//delete p0 characters from N0, then insert string s at P0
String &replace (int p0, int n0,const char *s, int n),//delete p0 start n0 characters, then insert first n characters of string s at P0
String &replace (int p0, int n0,const string &s),//delete p0 characters from N0, then insert string s at P0
String &replace (int p0, int n0,const string &s, int pos, int n),//delete p0 start N0 character, and then insert string s at P0 to start n characters from Pos
String &replace (int p0, int n0,int n, char c),//delete n0 characters beginning with p0, and then insert n characters C at p0
String &replace (iterator first0, iterator last0,const char *s);//replace the section between [First0,last0] with the string s
String &replace (iterator first0, iterator last0,const char *s, int n);//replace the section between [First0,last0] with the first n characters of S
String &replace (iterator first0, iterator last0,const string &s);//replace the section between [First0,last0] with string s
String &replace (iterator first0, iterator last0,int N, char c);//replace the section between [First0,last0] with n characters c
String &replace (iterator first0, iterator Last0,const_iterator first, const_iterator last);//Put [First0, LAST0) between the parts replaced by [First,last] between the strings


Insert function of String
String &insert (int p0, const char *s);
String &insert (int p0, const char *s, int n);
String &insert (int p0,const string &s);
String &insert (int p0,const string &s, int pos, int n);
First 4 functions Insert the first n characters of the POS in the string s in the P0 position
String &insert (int p0, int n, char c);//This function inserts n characters c at p0
Iterator insert (iterator it, char c);//insert character C at it to return the position of the post-insertion iterator
void Insert (iterator it, Const_iterator first, const_iterator last);//insert characters between [first,last] in it
void Insert (iterator it, int n, char c);//insert n characters c in it


string delete function
Iterator Erase (iterator first, iterator last);//Remove all characters between [First,last] and return the post-delete iterator
Iterator erase (iterator it);// Remove the character that it points to, return the position of the post-delete iterator
string &erase (int pos = 0, int n = npos), or delete the n characters starting at POS, and return the modified string

string:: Iterator or String::const_iterator declares an iterator variable, const_iterator does not allow the content of the iteration to be changed. Common iterator functions are:
Const_iterator begin () const;
Iterator begin ();                 //returns the starting position of string
Const_iterator end () const;
Iterator End ();                     //returns the position after the last character of String
Const_iterator rbegin () const;
Iterator Rbegin ();                 //returns the position of the last character of String
Const_iterator rend () const;
Iterator rend ();                     //returns the first character position of string before
Rbegin and rend are used to access from a backward forward iteration, by setting the iterator String::reverse_iterator, String::const_reverse_iterator implementation

There are several ways to initialize a string object with the definition and initialization of a 1.string object:
    1. String s1;//default constructor, S1 is an empty string
    2. String S2 (S1);//initializes S2 to a copy of S1
    3. String S3 ("value");//Initialize S3 to value
    4. String S4 (N, ' C ');//Initialize S4 to n copies of character ' C '
    5. String S5 (s4,0,3)//starts with a character labeled 0 in the S4 and takes 3 characters in a row to make a S5
    6. String s6 = S5 + "value",//value after S5, note that the + operator has at least one of the left and right operands of a string type
    7. Iterators are created, because string can be treated as a container object of characters, so you can pass two iterators to the constructor of the string class, copying the data between them into a string object of the heart.
#include "stdafx.h" #include <iostream> #include <string>using namespace std;int _tmain (int argc, _tchar* Argv[] {string S1 ("How is You"); string s2 (S1.begin (), S1.end ()), String S3 (S1.begin () +4,s1.begin () +7); cout<<s1 <<endl;cout<<s2<<endl;cout<<s3<<endl;return 0;}


The read-write of a 2.string object reads and writes a string object in two ways:
    1. Read from the standard input via CIN, CIN ignores all whitespace characters in the open question, reads the character until the white space character is encountered again, and the read terminates.
    2. Using getline to read entire lines of text, the Getline function accepts two parameters: an input stream object and a string object. The Getline function reads from the next line of the input stream and saves the read content to a string, but does not include a newline character . Unlike the input operator, Getline does not ignore the beginning of the line break. Even if it is the first character entered, Getline will stop reading and returning. If the first character is a line break, the string argument is set to an empty string.
The insert operation string of a 3.string object is generally composed of the first word match either, the tail word specifier, and any position insertion.
#include "stdafx.h" #include <iostream> #include <string>using namespace std;int _tmain (int argc, _tchar* Argv[] {string S1 ("Do");cout<< ' Initial size is: ' <<s1.size () <<endl;s1.insert (0, "how"); S1.append ( "You"), S1 = S1 + "do?"; cout<< "Final size is:" <<s1.size () <<endl;cout<<s1<<endl;return 0;}
The results of the program run as follows: The function can be obtained:
    1. The Insert function, the first parameter indicates the position of the insertion source string, the second parameter surface to insert the string, so the function can be used to achieve the string header, tail and arbitrary position of the strings insertion function.
    2. The Append function, which has only one input parameter, appends the string to the tail of the source string.
    3. Creates a new string by using the + implementation of the string's connection.
4. The replace operation is commonly used with the Replace function, there are three input parameters: the first is to indicate where to start overwriting from the string, the second is to indicate how many characters are removed from the source string, and the third is the value of the replacement string.
#include "stdafx.h" #include <iostream> #include <string>using namespace std;int _tmain (int argc, _tchar* Argv[]) {string S1 ("I Love you forever!"); cout<< "replace before:" <<s1<<endl;s1.replace (7,3, "Dachun");cout<< "after replace" <<s1<<endl; return 0;}
The results of the program operation are as follows: 5. Query operations queries commonly used functions are:
    1.     String::npos: This is a member variable in the String class, which is generally applied to determine the return value of a system query function, and, if equal to the value, indicates that there is no result value matching the query criteria.
    2. Find function: Finds the specified single character or group of characters in a string. Returns the starting position of the first match if found, and returns String::npos if no match is found. Typically there are two input parameters, one is the string to be queried, one is the starting position of the query, and the default starting position is 0.
    3. find_first_of function: To find in a string, the return value is the first character position that matches any character in the specified string, or String::npos if no matching content is found. Typically there are two input parameters, one is the string to be queried, one is the starting position of the query, and the default starting position is 0.
    4. find_last_of function: To find in a string, the return value is the last character position to match any character in the specified string, or String::npos if no matching content is found. Typically there are two input parameters, one is the string to be queried, one is the starting position of the query, and the default starting position is 0.
    5. find_first_not_of function: To find in a string, the return value is the first character position that does not match any character in the specified string, and returns String::npos if no match is found. Typically there are two input parameters, one is the string to be queried, one is the starting position of the query, and the default starting position is 0.
    6. find_last_not_of function: Finds in a string, returns the position of the character with the largest subscript value that does not match any character in the specified string, or returns String::npos if no matching content is found. Typically there are two input parameters, one is the string to be queried, one is the starting position of the query, and the default starting position is 0.
    7. RFind function: Finds the specified single character or group of characters on a string from the tail to the head, returns the start of the first match if found, and returns String::npos if no matching content is found. Typically there are two input parameters, one is the string to be queried, one is the starting position of the query, and the default starting position is 0.
#include "stdafx.h" #include <iostream> #include <string>using namespace std;int _tmain (int argc, _tchar* Argv[]) {string S1 ("What ' s your name? My name is TOM. How does it do? Fine,thanks. "); int n = s1.find ("your");cout<< "the First your pos:" <<n<<endl;n = S1.find ("You",;cout<< "the First you POS begin at: "<<n<<endl;n = s1.find_first_of (" ABCDE ");cout<<" find Pos when character wit Hin ABCDE: "<<n<<endl;n = s1.find_first_of (" ABCDE ", 3);cout<<" Find Pos when character within ABCDE from Third character: "<<n<<endl;return 0;}

The result of the program operation is as follows: 6. Delete character operations mainly with the erase function, there are two iterator input parameters, the characters represented between will be deleted.
#include "stdafx.h" #include <iostream> #include <string>using namespace std;int _tmain (int argc, _tchar* Argv[]) {string S1 ("What ' s your name? My name is TOM. How does it do? Fine,thanks. "); S1.erase (S1.begin (), S1.begin () +17);cout<< "After erase to S1 are:" <<s1<<endl;string s2 = "I love You Forever! "; S2.erase (S2.begin (), S2.end ());cout<< "After erase to S2 are" <<s2<<endl;return 0;
The result of the program operation is as follows: 7. The comparison operation is mainly an ASCII value to compare the size.    If the string S1 "is greater than" S2, it indicates that the first pair of different characters are encountered when comparing them, and the first different character in the string S1 transmitting the same position in the string S2 in the ASCII table. C + + STL provides a multi-clock string comparison method, each with their own characteristics. The simplest of these is the use of non-member overloaded operator functions operator==, operator!=, operator>, operator<, operator>=, and operator<=.

One of the STL: a string usage explanation

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.