|
|
|
|
|
|
|
the null character. When the compiler encounters the string ''Hi" in a program, it stores the three characters 'H', 'i', and '\0' into a three-element, anonymous (unnamed) char array as follows: |
|
|
|
|
|
|
|
|
The String is the only kind of C++ array for which there exists an aggregate constant-the string constant. Notice that in a C++ program, the symbols 'A' denote a single character, whereas the symbols "A" denote two: the character 'A' and the null character. |
|
|
|
|
|
|
|
|
In addition to string constants, we can create string variables. To do so, we explicitly declare a char array and store into it whatever characters we want to, finishing with the null character. Here's an example: |
|
|
|
|
|
|
|
|
char myStr[8]; // Room for 7 significant characters plus '\0'
myStr[0] = 'H';
myStr[1] = 'i';
myStr[2] = '\0'; |
|
|
|
 |
|
 |
|
|
String A collection of characters interpreted as a single item; in C++, a nullterminated sequence of characters stored in a char array. |
|
|
|
|
|
|
|
|
In C++, all strings (constants or variables) are assumed to be nullterminated. This convention is agreed upon by all C++ programmers and standard library functions. The null character serves as a sentinel value; it allows algorithms to locate the end of the string. For example, here is a function that determines the length of any string, not counting the terminating null character: |
|
|
|
|
|
|
|
|
int StrLength( /* in */ const char str[] )
// Precondition:
// str is a null-terminated string
// Postcondition:
// Function value == number of characters in str (excluding '\0') |
|
|
|
|
|