C / C + + Programming Notes: C + + string class and its application! New knowledge is coming again

Time:2021-4-20

In C + +, we can store strings in one of the following two ways:

(1) C language way to store strings (character array, character pointer, etc.) the next section discusses

(2) String classes (discussed in this article)

In this article, we will discuss the second method. String class is a part of C + + library, which supports many functions on C style string.

C / C + + Programming Notes: C + + string class and its application! New knowledge is coming again

 

C + + string class uses char array to store characters internally, but all memory management, allocation and null termination are handled by string class itself, which is why it is easy to use. Because of the vector like dynamic memory allocation, the length of C + + strings can be changed at run time. Because the string class is a container class, we can use iterators of other containers such as vectors, sets, and maps to iterate over all its characters, but usually we use a simple for loop to iterate over the characters and index them with the [] operator.

C + + string class has many functions to deal with string easily. The following code demonstrates the most useful of these.

C / C + + Programming Notes: C + + string class and its application! New knowledge is coming again

 

C / C + + Programming Notes: C + + string class and its application! New knowledge is coming again

 

As shown in the above code, we can get the length of the string through size () and length (), but length () is the preferred string. We can go through it + = Or append() to connect one string to another, but + = Is slightly slower than append() because each call + Creates a new string (creates a new buffer) and returns the bit cost of the string for many append operations.

Application:

Based on the above string functions, some applications are as follows:

C / C + + Programming Notes: C + + string class and its application! New knowledge is coming again

 

C / C + + Programming Notes: C + + string class and its application! New knowledge is coming again

 

Hope to help you~

In addition, if you want to better improve your programming ability, learn C language c + + programming! Overtaking on the curve, one step faster! I may be able to help you here~

C language c + + programming learning circle,QQ group 1090842465Click to enterWeChat official account: C language programming learning base

Share (source code, project video, project notes, basic introductory course)

Welcome to change and learn programming partners, use more information to learn and grow faster than their own thinking Oh!

Programming learning book sharing:

Programming learning video sharing: