beautypg.com

String operations, Declaration and initialization of string, Resetting size and capacity – HP Integrity NonStop H-Series User Manual

Page 132

background image

Click on the banner to return to the user guide home page.

©Copyright 1996 Rogue Wave Software

String Operations

In the following sections, we'll examine the standard library operations used to create and
manipulate strings.

Declaration and Initialization of string

The simplest form of declaration for a string simply names a new variable, or names a variable
along with the initial value for the string. This form was used extensively in the example graph
program given in

9 (

Example, Graphs

)

. A copy constructor also permits a string to be declared that

takes its value from a previously defined string.

string s1;
string s2 ("a string");
string s3 = "initial value";
string s4 (s3);

In these simple cases the capacity is initially exactly the same as the number of characters being
stored. Alternative constructors let you explicitly set the initial capacity. Yet another form allows
you to set the capacity and initialize the string with repeated copies of a single character value.

string s6 ("small value", 100);// holds 11 values, can hold 100
string s7 (10, '\n'); // holds ten newline characters

Initializing from Iterators

Finally, like all the container classes in the standard library, a string can be initialized using a pair of
iterators. The sequence being denoted by the iterators must have the appropriate type of elements.

string s8 (aList.begin(), aList.end());

Resetting Size and Capacity

As with the

vector

data type, the current size of a string is yielded by the size() member function,

while the current capacity is returned by capacity(). The latter can be changed by a call on the
reserve() member function, which (if necessary) adjusts the capacity so that the string can hold at
least as many elements as specified by the argument. The member function max_size() returns the
maximum string size that can be allocated. Usually this value is limited only by the amount of
available memory.

cout << s6.size() << endl;

This manual is related to the following products: