Mixed string and C-style code
We all know that you can use the following method to initialize a string object:
String s ("hello world !");
In fact, we can also achieve this in this way:
Char c [] = {'h', 'E', 'l', 'l', 'O', '', 'w', 'O ', 'R', 'l', 'D ','! ',' \ 0 '};
String s = c;
However, if array c does not end with a null character, the assignment above is incorrect.
In fact, any string literal value (that is, the above "hello world !" This form) can be replaced by an array of characters ending with null characters. Note the following:
1. You can use an array of characters ending with null characters to initialize a string object or assign a value to a string object.
2. In addition operations on string objects, you can use an array of characters ending with an empty character as one of the calculation objects, but not both of them. In addition operations of string, at least one object must be a string object. For example:
Char a [] = {'A', '\ 0 '};
Char B [] = {'B', '\ 0 '};
String c = "abdc ";
String d = "abcd" + a; // error. No string object exists on the right of the value assignment operation.
String e = a + B; // error. No string object exists on the right of the value assignment operation.
String f = c + a; // correct
A string object can be used to operate on an array of characters ending with null characters, but it cannot be used in turn. Character pointers cannot be operated using string objects. However, in order to complete the transformation from a string object to a character pointer, string provides a c_str member function (as the name suggests, it is the string pointer that returns c ):
String a = "hello world !";
Char * str = s; // Error
Const char * str = s. c_str (); // correct
However, this method cannot guarantee that the array returned by the c_str function is always valid, because if the value of s is changed in subsequent operations, the array returned may change. For example:
String d = "abc ";
Const char * c = d. c_str ();
Cout <c <endl;
D = "efg ";
Cout <c <endl;
The output result is:
Abc
Efg
We can see that the string object has changed. Even if we haven't assigned the changed value to c again, the result still changes. So if we want to save the current string, we 'd better copy the result again.