Details of common function usage in c ++ in string, details of string function usage

Source: Internet
Author: User

Details of common function usage in c ++ in string, details of string function usage
Note that it is not CString

The reason why the char * string is discarded and the string class in the C ++ standard library is used is because it is compared with the former, and does not have to worry about whether the memory is sufficient, the string length, and so on. It also appears as a class, the integrated operation functions are sufficient to meet our needs in most cases (or even 100%. We can use = for the value assignment operation, = for comparison, + for concatenation (isn't it easy ?). We can think of it as the basic data type of C ++.

Okay, go to the topic .........

First, to use the string type in our program, we must include the header file .

As follows:

# Include // Note that string. h string. h is not the C string header file.

# Include

Using namespace std;

1. Declare a C ++ string

It is easy to declare a string variable:

String Str;

In this way, we declare a string variable, but since it is a class, there are constructors and destructor. The preceding Declaration does not include any parameters, so the default constructor of string is used directly. What this function does is to initialize Str as an empty string. The constructor and destructor of the String class are as follows:

A) string s; // generate an empty string s

B) string s (str) // copy the constructor to generate a copy of str

C) string s (str, stridx) // use the portion of the string 'start with stridx 'as the initial value of the string.

D) string s (str, stridx, strlen) // take the part of the string 'strx' that begins with stridx and has a maximum length of strlen' as the initial value of the string.

E) string s (cstr) // use the C string as the initial value of s.

F) string s (chars, chars_len) // use the character chars_len before the C string as the initial value of string s.

G) string s (num, c) // generate a string containing num c characters

H) string s (beg, end) // use the characters in the interval beg; end (excluding end) as the initial values of string s.

I) s .~ String () // destroy all characters and release the memory

It's easy. I will not explain it.

2. String operation functions

Here is the focus of C ++ strings. I will first list various operation functions. People who do not like to read all functions can find their favorite functions here, let's look at his detailed explanation later.

A) =, assign () // assign a new value

B) swap () // exchanges the content of two strings

C) + =, append (), push_back () // Add characters at the end

D) insert () // insert characters

E) erase () // Delete characters

F) clear () // Delete All characters

G) replace () // replace character

H) + // concatenate strings

I) = ,! =, <, <=,>, >=, Compare () // compare strings

J) size (), length () // number of returned characters

K) max_size () // maximum number of returned characters

L) empty () // determines whether the string is null.

M) capacity () // returns the character capacity before the reallocation

N) reserve () // retain a certain amount of memory to accommodate a certain number of characters

O) [], at () // access a single character

P)>, getline () // read a value from stream

Q) <// write the value to stream

R) copy () // assign a value to a C_string

S) c_str () // return the content as C_string

T) data () // returns the content in the form of a character array

U) substr () // returns a substring.

V) search functions

W) begin () end () // provides iterator support similar to STL

X) rbegin () rend () // reverse iterator

Y) get_allocator () // return to the Configurator

The following details:

Conversion of 2.1 C ++ strings and C strings

The C_string method provided by C ++ is to use data (), c_str (), and copy (), where data () returns the string content in the form of a character array, but does not add '/0 '. C_str () returns an array of characters ending with '/0', while copy () copies or writes the content of the string to an existing c_string or character array. The C ++ string does not end with '/0. I suggest using C ++ strings in a program unless you have to use c_string. As it is only a brief introduction, a detailed introduction is skipped. Anyone who wants to know more about the precautions during use can leave a message (to my inbox ). I will explain it in detail.

2.2 size and capacity functions

A C ++ string has three types of sizes: a) the number of existing characters. The functions are size () and length (), which are equivalent. Empty () is used to check whether the string is null. B) max_size () refers to the maximum number of characters that can be contained in the current C ++ string. It is likely to be related to machine restrictions or the size of continuous memory in the position of the string. We generally don't need to care about him. It should be enough for us. If it is not enough, the system will throw the length_error exception c) capacity () the maximum number of characters that the string can contain before the memory is reassigned. Another thing to note here is the reserve () function, which re-allocates the memory for the string. The size of the reallocation is determined by the parameter. The default parameter is 0. At this time, the unforced reduction of the string is performed.

It is also necessary to repeat the questions about conversion between C ++ strings and C strings. Many people may encounter such problems, your own program needs to call others' functions and classes (such as database connection function Connect (char *, char *)), however, others' function parameters are in the char * format. We know that the character arrays returned by c_str () and data () are owned by this string, therefore, it is a const char *. to be used as a parameter of the function mentioned above, you must copy it to a char *. Our principle is that it is not used without using a C string. Then, our processing method is: if this function does not modify the content of the parameter (that is, char *), we can Connect (char *) UserID. c_str (), (char *) PassWD. c_str (), but it is dangerous at this time, because the converted string can be modified (you can try it yourself if you are interested ), so I stress that the parameter must be copied to a char * unless it is modified during function call. Of course, the more secure way is to copy everything to a char. At the same time, we also pray that the experts who still use the C string for programming (say they are not a good expert at all, maybe they will start programming when we are still wearing kaixiao pants, haha ...) Write Functions are more standardized, so we do not have to perform forced conversion.

2.3 element access

We can use the subscript operator [] and 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 (). If the index fails, it will cause undefined behavior. At () checks. If the index is invalid when at () is used, an out_of_range exception is thrown.

The [] operator of const string a; is still valid for the index value of a. length (), and the return value is '/0 '. In other cases, the. length () index is invalid. Example:

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 '/0'

Str. at (Str. length (); // throw out_of_range

Cstr. at (Cstr. length () // throw out_of_range

I do not agree with the following reference or pointer assignment:

Char & r = s [2];

Char * p = & s [3];

This is because r and p are invalid immediately after a reallocation. The method to avoid this problem is not to use it.

2.4 comparison functions

C ++ strings support common comparison operators (>,>=, <,<=, == ,! =), Or even comparison between string and C-string (for example, str <"hello "). When using the>, >=, <, <= operators, the characters are compared alphabetically according to the "current character characteristics. The character before the dictionary sorting is small, and the comparison order is from the beginning to the back. When an unequal character is encountered, the size of the two strings is determined based on the comparison results of the two characters at the position. At the same time, string ("aaaa ")

Another powerful comparison function is the member function compare (). It supports multi-parameter processing and comparison with index values and length locating substrings. Return an integer to indicate the comparison result. The returned value is 0-equal> 0-greater than <0-less. Example:

String s ("abcd ");

S. compare ("abcd"); // return 0

S. compare ("dcba"); // return a value smaller than 0

S. compare ("AB"); // return a value greater than 0

S. compare (s); // equal

S. compare (, s,); // use "AB" and "cd" to compare values smaller than zero.

S. compare (, "bcx", 2); // compare it with "bc" and "bc.

How is it? Full functions! What? Cannot satisfy your appetite? Well, there is a more personalized comparison algorithm. First, let's give a note that we use the STL comparison algorithm. What? Do you know nothing about STL? You need to repair it again!

2.5 change content

This is a large part of string operations.

First, assign values. The first assign value method is of course using the operator =. The new values can be string (for example, s = ns) and c_string (for example, s = "gaint ") or even a single character (for example, s = 'J '). You can also use the member function assign (), which allows you to assign values to strings more flexibly. Let's give an example:

S. assign (str); // not to mention

S. assign (str,); // If str is "iamangel", "ama" is assigned to the string.

S. assign (str, 2, string: npos); // assign the string 'str' to s from index 2 to the end.

S. assign ("gaint"); // do not mention

S. assign ("nico", 5); // assign 'n' 'I ''c' o'/0' to the string

S. assign (5, 'x'); // assign five x to the string.

There are three methods to clear the string: s = "; s. clear (); s. erase (); (I think it is easier to give examples to others than to speak !).

String provides many functions for insert, erase, replace, and adding characters.

First, add characters (in this example, add on the tail). functions include + =, append (), and push_back ().

Example:

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,); // it does not explain the interpretation of the function parameter assign.

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 understand STL easily.

Maybe you need to insert a string somewhere in the middle of the string. At this time, you can use the insert () function. This function requires you to specify an index for the insert Location, the inserted string is placed behind this index.

S. insert (0, "my name ");

S. insert (1, str );

This form of insert () function does not support the input of a single character. At this time, a single character must be written as a string (disgusting ). Since you are disgusted, You have to continue reading the following: To insert a single character, the insert () function provides two overload functions for inserting a single character: insert (size_type index, size_type num, chart c) and insert (iterator pos, size_type num, chart c ). Size_type is an unsigned integer and iterator is char *. Therefore, you cannot call the insert function as follows: insert (, 'J '); in this case, which one will the first parameter be converted? So you must write: insert (string: size_type) 0, 1, 'J ')! The second form refers to the use of the iterator to insert characters, which will be mentioned later. By the way, many operations on string use the STL iterator, And He tries his best to keep it close to STL.

There are also several ways to delete the function erase !), There are also several replace () replace functions.

For example:

String s = "il8n ";

S. replace (, "nternationalizatio"); // replace the two values starting from Index 1 with the C_string

S. erase (13); // delete all data starting from Index 13

S. erase (); // Delete 5 from index 7

2.6 extract substrings and string connections

The substring function is substr (). The format is as follows:

S. substr (); // returns all content of s.

S. substr (11); // substring after index 11

S. substr (5, 6); // 6 characters starting from index 5

The function that combines the two strings is +. (If you do not understand, call 120)

2.7 input/output operations

1.> Read a string from the input stream.

2. <write a string to the output stream.

Another function is getline (). It reads a line of content from the input stream until it encounters a branch character or reaches the end of the file.

2.8 search and search

There are many search 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 in the character range that meets the search criteria. If no target is found, npos is returned. Parameters of all functions are described as follows:

The first parameter is the searched object. The second parameter (optional) indicates the Search Start index in the string, and the third parameter (optional) indicates the number of characters in the search. It is relatively simple. If you don't want to understand it, you can give it to me. I will answer it carefully. Of course, more powerful STL search will be mentioned later.

Finally, let's talk about the meaning of npos. The string: npos type is string: size_type. Therefore, once an index needs to be compared with npos, the index value must be string: size) type. In more cases, we can directly compare the function with npos (for example, if (s. find ("jia") = string: npos )).

Constructor of the string class:

String (const char * s); // use the c string s for initialization

String (int n, char c); // initialize with n characters c

In addition, the string class also supports default constructor and copy constructor, such as string s1; string s2 = "hello. If the constructed string is too long to be expressed, the length_error exception is thrown.

String character operations:

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. However, the at function provides a range check and throws an out_of_range exception when the current string is out of bounds, the subscript operator [] does not provide access check.

Const char * data () const; // returns a non-null ending c character array

Const char * c_str () const; // returns a null-terminated c string.

Int copy (char * s, int n, int pos = 0) const; // copy the n characters starting with pos in the current string to the character array starting with s, and return the actual number of copies

Feature description of string:

Int capacity () const; // returns the current capacity (that is, the number of elements in the string that can be stored without adding memory)

Int max_size () const; // returns the maximum length of a 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 null

Void resize (int len, char c); // set the current size of the string to len and fill the missing part with character c.

Input and Output operations of the string class:

String type heavy-duty operator> used for input, also heavy-duty operator <used for output operations.

The getline (istream & in, string & s) function is used to read strings from the input stream in to s and separate them with line breaks '\ n.

String Value assignment:

String & operator = (const string & s); // assign string s to the current string

String & assign (const char * s); // use the c-type string s to assign a value

String & assign (const char * s, int n); // assign values with n characters starting with string s

String & assign (const string & s); // assign string s to the current string

String & assign (int n, char c); // assign a value to the current string with n characters c

String & assign (const string & s, int start, int n); // assign the n characters starting from start in string s to the current string

String & assign (const_iterator first, const_itertor last); // assign the part between the first and last iterators to the string

String connection:

String & operator ++ = (const string & s); // connects string s to the end of the current string

String & append (const char * s); // connect string s of the c type to the end of the current string

String & append (const char * s, int n); // connect the first n characters of the c-type string s to the end of the current string

String & append (const string & s); // same as operator + = ()

String & append (const string & s, int pos, int n); // connects n characters starting from pos in string s to the end of the current string

String & append (int n, char c); // Add n characters to the end of the current string

String & append (const_iterator first, const_iterator last); // link the part of the iterator first and last to the end of the current string

String comparison:

Bool operator = (const string & s1, const string & s2) const; // compare whether two strings are equal

Operator ">", "<", "> =", "<= ","! = "Both are reloaded for string comparison;

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; // compare the size of s and the string consisting of n characters starting from pos of the current string

Int compare (int pos, int n, const string & s, int pos2, int n2) const; // compare the size of a string consisting of n characters starting from pos and n2 characters starting from 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;

When the compare function is>, 1 is returned. If the value is <,-1 is returned. If the value is =, 0 is returned.

Substring of string:

String substr (int pos = 0, int n = npos) const; // returns a string consisting of n characters starting with pos.

String exchange:

Void swap (string & s2); // exchange the value of the current string and s2

String-type lookup functions:

Int find (char c, int pos = 0) const; // start from pos to find the position of character c in the current string

Int find (const char * s, int pos = 0) const; // start from pos to find the position of string s in the current string

Int find (const char * s, int pos, int n) const; // start from pos to find the position of the First n characters in string s in the current string

Int find (const string & s, int pos = 0) const; // search for the position of string s in the current string from pos

// Return the location when the search is successful. If the search fails, return the string: npos value.

Int rfind (char c, int pos = npos) const; // search for the position of character c in the current string from the pos to the forward

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;

// Start from the pos and start from the back to the front to find the position of the string consisting of the First n characters in string s in the current string. If the string fails, return the value of string: npos.

Int find_first_of (char c, int pos = 0) const; // search for the position where character c appears for the first time 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;

// Start from pos to find the position of the first character in the array consisting of the First n characters of s in the current string. 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;

// Find the position of the first character not in the string s from the current string. If the string fails to appear, string: npos is returned.

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, but they are searched forward from the back.

Replacement functions of the string class:

String & replace (int p0, int n0, const char * s); // Delete the n0 characters starting with p0, and insert the string s at p0

String & replace (int p0, int n0, const char * s, int n); // Delete n0 characters starting with p0, insert the first n characters of string s in p0.

String & replace (int p0, int n0, const string & s); // Delete the n0 characters starting with p0, and insert the string s at p0

String & replace (int p0, int n0, const string & s, int pos, int n); // Delete n0 characters starting with p0, then insert n characters starting from pos in string s at p0

String & replace (int p0, int n0, int n, char c); // Delete n0 characters starting with p0, and then insert n characters c at p0

String & replace (iterator first0, iterator last0, const char * s); // replace the parts between [first0, last0) with the string s

String & replace (iterator first0, iterator last0, const char * s, int n); // replace the portion between [first0, last0) with the first n characters of s

String & replace (iterator first0, iterator last0, const string & s); // replace the parts between [first0, last0) with the string s

String & replace (iterator first0, iterator last0, int n, char c); // replace the parts between [first0, last0) with n characters c

String & replace (iterator first0, iterator last0, const_iterator first, const_iterator last); // replace the parts between [first0, last0) with strings between [first, last)

Insert functions of the 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 four functions Insert the first n characters starting with pos in the string s at the p0 position

String & insert (int p0, int n, char c); // This function inserts n characters in p0 c

Iterator insert (iterator it, char c); // insert character c in it to return the position of the iterator after insertion

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 in it

Delete functions of the string class

Iterator erase (iterator first, iterator last); // deletes all characters between [first, last) and returns the position of the iterator after deletion.

Iterator erase (iterator it); // deletes the characters it points to and returns the position of the iterator after deletion.

String & erase (int pos = 0, int n = npos); // Delete the n characters starting with pos and return the modified string

String type iterator processing:

The string class provides the iterator for Traversing forward and backward. The iterator provides the syntax for accessing each character, similar to pointer operations. The iterator does not check the range.

Use string: iterator or string: const_iterator to declare the iterator variable. const_iterator cannot change the content of the iteration. Common iterator functions include:

Const_iterator begin () const;

Iterator begin (); // returns the starting position of the 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 of the string.

Rbegin and rend are used for iterative access from the back and forward. They are implemented by setting the iterator string: reverse_iterator, string: const_reverse_iterator

String stream processing:

Implemented by defining ostringstream and istringstream variables, Header file

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 = "", s4 = "test"

Ostringstream OS;

OS <

Cout <

Related Article

E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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.