C ++ string usage

Source: Internet
Author: User

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.

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 problem of converting C ++ strings and C strings. Many people will encounter such problems, your own program needs to call others' functions and classes (such as the database connection function connect (char *, char *), but others' function parameters use the char * format, we know that the character array returned by c_str () and data () is owned by this string, so it is a const char *. to be used as a parameter of the function mentioned above, it must also be copied to a char *, but our principle is that the C string is not used. 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. In addition, another powerful comparison function of string ("aaaa") 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 ');

 

String operations are not a small topic. In Standard C ++, string classes become a standard. The reason why char * strings are discarded is to use the string classes in the C ++ standard library, compared with the former, he does not have to worry about memory size, string length, and so on. As a class, his integrated operation functions are sufficient to meet our needs in most cases.
Next we will first learn how to use the string class from some examples.
1)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S ("hehe ");
Cout <S <Endl;
Cin. Get ();
}
2)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
Char CHS [] = "hehe ";
String S (CHS );
Cout <S <Endl;
Cin. Get ();
}
3)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
Char CHS [] = "hehe ";
String S (CHS,); // specify to start from CHS Index 1, and finally copy 3 bytes
Cout <S <Endl;
Cin. Get ();
}
4)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S1 ("hehe ");
String S2 (S1 );
Cout <S2 <Endl;
Cin. Get ();
}
5)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S1 ("hehe", 2, 3 );
String S2 (S1 );
Cout <S2 <Endl;
Cin. Get ();
}
6)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
Char CHS [] = "hehe ";
String S (CHS, 3); // construct the first three characters of CHS as the initial values.
Cout <S <Endl;
Cin. Get ();
}
7)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S (10, 'k'); // allocate 10 characters. The initial values are all 'K'
Cout <S <Endl;
Cin. Get ();
}
// The above is the construction method of string-type instances, which is very simple.

9)
// New Value
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S (10, 'k'); // allocate 10 characters. The initial values are all 'K'
Cout <S <Endl;
S = "hehehehe ";
Cout <S <Endl;
S. Assign ("kdje ");
Cout <S <Endl;
S. Assign ("fkdhfkdfd", 5); // reassign the first 5 elements of the specified string
Cout <S <Endl;
Cin. Get ();
}
10)
// Swap method exchange
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S1 = "hehe ";
String S2 = "gagaga ";
Cout <"S1:" <S1 <Endl;
Cout <"S2:" <S2 <Endl;
S1.swap (S2 );
Cout <"S1:" <S1 <Endl;
Cout <"S2:" <S2 <Endl;
Cin. Get ();
}
11)
// + =, Append (), push_back () add characters at the end
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "hehe ";
S + = "Gaga ";
Cout <S <Endl;
S. append (""); // The append () method can be used to add strings.
Cout <S <Endl;
S. push_back ('k'); // The push_back () method can only add one character...
Cout <S <Endl;
Cin. Get ();
}
12)
// Insert () inserts characters. In fact, insert is well used, which is the same as other insert operations.
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "hehe ";
S. insert (0, "Header"); // insert in the header
S. insert (S. Size (), "tail"); // Insert at the end
S. insert (S. Size ()/2, "intermediate"); // insert in the middle
Cout <S <Endl;
Cin. Get ();
}
13)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg ";
S. Erase (0, 1); // from index 0 to index 1, 'A' is deleted'
Cout <S <Endl;
// In fact, you can also use the replace method to perform the delete operation.
S. Replace (, ""); // Replace the characters in the specified range with "", that is, they are deleted in disguise.
Cout <S <Endl;
Cin. Get ();
}

14)
// Clear () delete all characters
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg ";
Cout <S. Length () <Endl;
S. Clear ();
Cout <S. Length () <Endl;
// Use the earse method to delete all data in disguise
S = "dkjfd ";
Cout <S. Length () <Endl;
S. Erase (0, S. Length ());
Cout <S. Length () <Endl;

Cin. Get ();
}
15)
// Replace () Replacement character
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg ";
S. Replace (2, 3 ,"!!!!! "); // Replace all the three-byte characters starting from index 2 "!!!!! "
Cout <S <Endl;
Cin. Get ();
}
16)
// = ,! =, <, <=,>, >=, Compare () compares strings
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S1 = "abcdefg ";
String S2 = "abcdefg ";
If (S1 = S2) cout <"S1 = S2" <Endl;
Else cout <"S1! = S2 "<Endl;

If (S1! = S2) cout <"S1! = S2 "<Endl;
Else cout <"S1 = S2" <Endl;

If (S1> S2) cout <"S1> S2" <Endl;
Else cout <"S1 <= S2" <Endl;

If (S1 <= S2) cout <"S1 <= S2" <Endl;
Else cout <"S1> S2" <Endl;

Cin. Get ();
}
17)
// Size (), length () returns the number of characters
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg ";
Cout <S. Size () <Endl;
Cout <S. Length () <Endl;

Cin. Get ();
}
18)
// Max_size () returns the maximum possible number of characters
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg ";
Cout <S. max_size () <Endl;

Cin. Get ();
}
19)
// Empty () determines whether the string is null
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S;
If (S. Empty ())
Cout <"s is empty." <Endl;
Else
Cout <"s is not empty." <Endl;

S = S + "abcdefg ";
If (S. Empty ())
Cout <"s is empty." <Endl;
Else
Cout <"s is not empty." <Endl;

Cin. Get ();
}
20)
// [], At () access a single character
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg1111 ";

Cout <"use []:" <Endl;
For (INT I = 0; I <S. Length (); I ++)
{
Cout <s [I] <Endl;
}
Cout <Endl;

Cout <"use at ():" <Endl;
For (INT I = 0; I <S. Length (); I ++)
{
Cout <S. at (I) <Endl;
}
Cout <Endl;

Cin. Get ();
}
21)
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg1111 ";

Const char * chs1 = S. c_str ();
Const char * chs2 = S. Data ();

Cout <"use at ():" <Endl;
Int I;
For (I = 0; I <S. Length (); I ++)
{
Cout <"c_str ():" <chs1 [I] <Endl;
Cout <"data ():" <chs2 [I] <Endl;
}
Cout <"c_str ():" <chs1 <Endl;
Cout <"data ():" <chs2 <Endl;
Cout <Endl;

Cin. Get ();
}
22)
// Substr () returns a substring.
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg1111 ";

String STR = S. substr (5, 3); // three bytes starting from index 5
Cout <STR <Endl;

Cin. Get ();
}
23)
// Find the Function
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg1111 ";
String Pattern = "FG ";
String: size_type Pos;
Pos = S. Find (pattern, 0); // search for the header index that matches the string "F" starting from index 0
Cout <POS <Endl;
String STR = S. substr (Pos, pattern. Size ());
Cout <STR <Endl;
Cin. Get ();
}
24)
// Begin () end () provides iterator support similar to STL
# Include <string>
# Include <iostream>
Using namespace STD;

Void main ()
{
String S = "abcdefg1111 ";
For (string: iterator iter = S. Begin (); iter! = S. End (); ITER ++)
{
Cout <* ITER <Endl;
}
Cout <Endl;

Cin. Get ();
}
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.

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.