We all know that you can initialize a string object in the following way:
string s ("Hello world!");
We can actually do that in this way:
Char c[] = {' h ', ' e ', ' l ', ' l ', ' o ', ', ' w ', ' O ', ' r ', ' L ', ' d ', '! ', ' + '};
string s = C;
However, if the array C is not terminated with a null character, then the above assignment is incorrect.
In fact, any occurrences of string literals (that is, the "Hello world!" above "This form" can be replaced by a character array that ends with a null character. Note the following points:
1. You can initialize a string object or assign a value to a string object by using a character array that ends with a null character
2. In the addition operation of a string object, an array of characters ending with a null character can be used as one of the operands, but not both. In the addition operation of string, at least one is guaranteed to be a string object . For example:
Char a[] = {' A ', ' + '};
Char b[] = {' B ', ' n '};
String c = "ABDC";
String d = "ABCD" + A; Error, no string object to the right of assignment operation
string e = A+b; Error, no string object to the right of assignment operation
string f = C +a; That's right
A string object can be manipulated with an array of characters at the end of a null character, but not in turn. You cannot use a string object to do anything to a character pointer. However, to complete the transition from a string object to a character pointer, string specifically provides a C_STR member function (as the name implies, a string pointer that returns C):
String a = "Hello world!";
char *str = s; Error
const char *STR = S.C_STR (); That's right
However, such a notation does not guarantee that the array returned by the C_STR function is valid, because if the subsequent operation changes the value of S, the previously returned array may be changed. Like what:
String d = "abc";
const char *c = D.C_STR ();
cout << C <<endl;
D = "EFG";
cout << c<< Endl;
The result of the output is:
Abc
Efg
You can see that the string object has changed, even though we haven't re-assigned the changed value to C, but the result is still the same. So if we want to save the current string, it's best to copy the result again.
Mixing string objects with C-style code