String common function usage in C + + summary _c language

Source: Internet
Author: User
Tags int size

Introduction to String class functions in standard C + +

Look, it's not CString.
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 + +.

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
#include <string>
using namespace Std;

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;   //generating an empty string s
B        string S (str)//Copy constructors generate a replica of STR
C)       string s (str,stridx)// Stridx the part of String str "starting at position" as the initial value of the string
D)       string s (Str,stridx,strlen)//String str inside The portion beginning 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)//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)//Destroy all characters in interval beg;end (not including end) as the initial value of string S
i)       s.~string ()//Free memory The
is simple, and I don't explain it.

2. String manipulation function
Here is the focus of the C + + string, I first list the various operation functions, do not like to read all the functions of the person can find their favorite function, and then look at his detailed explanation.
a) =,assign ()     //Assigning new value
B) swap ()     //Exchange two string contents
C) +=,append ( ), push_back ()///at tail add character
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 ()     //Returns the number of characters
K) max_size ()//return the possible maximum number of characters
L) empty ()    //Judge whether the string is empty
m) capacity ()// Returns the character capacity before reassignment
N) reserve ()///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 <<   //To write a value to stream
R) copy ()//Assign a value to a c_string
C_str ()//return content to c_string with
T) data ( //Returns the content as a character array
U) substr ()//Returns a substring
V) lookup function
W) begin () end ()//provide iterator similar to STL support
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 '/0 '. C_STR () returns an array of characters ending with '/0 ', while copy () copies or writes the contents of the string to an existing c_string or character array. C + + string does not end with '/0 '. 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 number of existing 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 issue of C + + string and C string conversions, and many people will encounter problems where their own programs call others ' functions, classes, and so on (such as database connection function connect (char*,char*)), but others ' function parameters The number is 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* and must be copied to a char* as a parameter to the function mentioned above. Our principle is not to use the C string without using it. 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 '/0 '. 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 (3); Ok
STR[100]; Undefined behavior (100); Throw Out_of_range
Str[str.length ()]//undefined behavior
Cstr[cstr.length ()]//return '/0 ' (Str.length ());//throw Out_of_range (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
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"); ("ABCD"); return 0 ("DCBA"); Returns a value less than 0 ("AB"); Returns a value greater than 0 (s); Equal (0,2,s,2,2); Compare "AB" with "CD" for less than 0 (1,2, "bcx", 2); Compare "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 personalized comparison algorithm behind it. First give a hint, using the STL comparison algorithm. What the? Is it all Greek to STL? 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 '/0 ' 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 feel more and more easy to understand for example than to talk 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 possible for you to invoke the Insert function: Insert (0,1, ' J '), where is the first argument converted to? So you have to write: 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 a function there are several forms of erase (), which are very 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 (e.g. if (S.find ("jia") = = String::npos).

Constructor of String class:
String (const char *s); Class with C string S.
string (int N,char c); Class with N-character C
In addition, the string class also supports default constructors and copy constructors, such as String s1;string s2= "Hello," which is the correct notation. Length_error exception is thrown when the constructed string is too long to be expressed

Character operations for string classes:
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 range check and throws a Out_of_range exception when the bounds are crossed, and the subscript operator [] does not provide check access.
const char *data () const;//returns a non-null terminated array of C characters
const char *C_STR () const;//returns a null-terminated C string
int copy (char *s, int n, int pos = 0) const;//copies n characters in the current string starting with Pos to an array of characters starting with S, returning the number of actual copies

Description of the attribute of string:
int capacity () const; Returns the current capacity (that is, the number of elements in string that do not need 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 character C

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

string Assignment:
string &operator= (const string &s);//Assign the string s to the current string
String &assign (const char *s);////C String s assignment
String &assign (const char *s,int n);/////= n-word assignments value with C string s
String &assign (const string &s);//Assign the string s to the current string
string &assign (int n,char c);//Assign value to the current string with n characters c
String & Assign (const string &s,int start,int N) assignments to the current string
string &assign (const_iterator first, the N word from start in the string s). Const_itertor last);//Assign the portion between the primary and last iterators to the string

String connection:
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 the C type string s are fonts to the end of the current string
string &append ( Const string &s);   //operator+= ()
String &append (const string &s,int pos,int N); Fonts The n-word at the beginning of the string s from the Pos to the end of the current string
string &append (int n,char c);       // Adds n characters c
string &append (Const_iterator First,const_iterator last) at the end of the current string;//connects the portion of the iterator first and last to the end of the current string

Comparison of String:
BOOL operator== (const string &s1,const string &s2) const;//compare two strings for equality
Operators ">", "<", ">=", "<=", "!=" are overloaded for string comparisons;
int compare (const string &s) const;//compares the current string and the size of s
int compare (int pos, int n,const string &s) const;//Compare the current string of n characters from Pos to the size of s
int compare (int pos, int n,const string &s,int pos2,int n2) const;// Compares the size of a string of n characters from the current string beginning with a POS to a N2 character that starts 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;
Compare function returns 0 when 1,< returns -1,== at >
Substring of string:
String substr (int pos = 0,int n = NPOs) const;//return of N-character strings starting with Pos

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

Lookup function for string class:
int find (char c, int pos = 0) const;//Look for the character C at the position of the current string from the POS
int find (const char *s, int pos = 0) const;//The position of the string s in the current string starting from Pos
int find (const char *s, int pos, int n) const;//The position of the first n characters in the string s in the current string starting from the POS
int find (const string &s, int pos = 0) const;//The position of the string s in the current string starting from Pos
Returns the location of the String::npos when the lookup succeeds, and the failure returns the value of the
int RFind (char c, int pos = NPOs) const;//Find 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;
From the beginning of the POS find the position of the first n characters in the string s in the current string, successfully return to the position, and return the value of String::npos when the failure occurs
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;
Starts from the POS to find the position of the first character in the current string in an array of the top n characters of S. Lookup 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 that is not in string s from the current string, and 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, just looking forward from the back

substitution function for string class:
String &replace (int p0, int n0,const char *s)//delete p0 characters starting from N0, then insert string s at P0
String &replace (int p0, int n0,const char *s, int n);//delete p0 characters that are starting with the, and then insert the first n characters of the string s at N0
String &replace (int p0, int n0,const string &s)//delete p0 characters starting 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 characters, then insert n characters from Pos in string s at P0
String &replace (int p0, int n0,int n, char c);//delete n0 characters starting p0, then insert n characters at P0
String &replace (iterator first0, iterator last0,const char *s);//replace the portion between [first0,last0) with the string s
String &replace (iterator first0, iterator last0,const char *s, int n);//Replace the part between [First0,last0] with the first n characters of S
String &replace (iterator first0, iterator last0,const string &s);//Replace the part between [First0,last0) with string s
String &replace (iterator first0, iterator last0,int N, char c);//replace the portion between [first0,last0) with n characters c
String &replace (iterator first0, iterator last0,const_iterator-I, const_iterator last);//Put [First0, LAST0) is replaced by a string between [First,last]

Insert function for String class:
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);
The first 4 functions insert the first n characters of the POS in the string s at 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 inserted post iterator
void Insert (iterator it, Const_iterator, const_iterator last);//insert characters between [first,last] at it
void Insert (iterator it, int n, char c);//insert n characters C at it

Delete function for String class
Iterator Erase (iterator primary, iterator last);//delete all characters between [First,last], return the position of the post-deletion iterator
Iterator Erase (iterator it); Remove the character that it points to, and return the position of the post-deletion iterator
String &erase (int pos = 0, int n = npos);//delete the N-character at the beginning of the POS, return the modified string

Iterator processing for string classes:
The string class provides iterator iterator for forward and backward traversal, which provides the syntax to access individual characters, similar to pointer operations, without the iterator checking the scope.


declares an iterator variable with string::iterator or String::const_iterator, and Const_iterator does not allow changes to the contents of the iteration. 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 previous
Rbegin and Rend of the first character position of string used for iterative access from the backward forward, by setting the iterator string::reverse_iterator,string: : Const_reverse_iterator implements the

String flow processing:
Implementing the,<sstream> header file by defining Ostringstream and Istringstream variables
For example:
String input ("Hello,this is a Test");
Istringstream is (input);
String s1,s2,s3,s4;
is>>s1>>s2>>s3>>s4;//s1= "Hello,this", s2= "is", s3= "a", s4= "test"
Ostringstream os;
Cout<<os.str ();

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: 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.