string
CharacteristicsClass string
provides member functions for gathering information about a string
’s size, length, capacity, maximum length and other characteristics. A string
’s size or length is the number of characters currently stored in the string
. A string
’s capacity is the number of characters that can be stored in the string
without allocating more memory. The capacity of a string
must be at least equal to the current size of the string
, though it can be greater. The exact capacity of a string
depends on the implementation. The maximum size is the largest possible size a string
can have. If this value is exceeded, a length_error
exception is thrown. Figure 21.5 demonstrates string
class member functions for determining various characteristics of string
s.
The program declares empty string string1
(line 10) and passes it to function printStatistics
(line 13). Function printStatistics
(lines 41–46) takes a reference to a const string
as an argument and outputs the capacity (using member function capacity
), maximum size (using member function max_size
), size (using member function size
), length (using member function size
) and whether the string
is empty (using member function empty
). The initial call to printStatistics
indicates that the initial values for the size and length of string1
are 0
.
The size and length of 0
indicate that there are no characters stored in string
. Recall that the size and length are always identical. In this implementation, the maximum size is 4,294,967,294. Object string1
is an empty string
, so function empty
returns true
.
Line 17 inputs a string. In this example, "tomato soup"
is input. Because a space character is a delimiter, only "tomato"
is stored in string1
; however, "soup"
remains in the input buffer. Line 21 calls function printStatistics
to output statistics for string1
. Notice in the output that the length is 6
and the capacity is 15
.
Line 24 reads "soup"
from the input buffer and stores it in string1
, thereby replacing "tomato"
. Line 27 passes string1
to printStatistics
.
Line 29 uses the overloaded +=
operator to concatenate a 46-character-long string to string1
. Line 31 passes string1
to printStatistics
. The capacity has increased to 63
elements and the length is now 50
.
Line 34 uses member function resize
to increase the length of string1
by 10
characters. The additional elements are set to null characters. The output shows that the capacity has not changed and the length is now 60
.