beautypg.com

Assignment, append and swap, Character access – HP Integrity NonStop H-Series User Manual

Page 133

background image

cout << s6.capacity() << endl;
s6.reserve(200); // change capacity to 200
cout << s6.capacity() << endl;
cout << s6.max_size() << endl;

The member function length() is simply a synonym for size(). The member function resize()
changes the size of a string, either truncating characters from the end or inserting new characters.
The optional second argument for resize() can be used to specify the character inserted into the
newly created character positions.

s7.resize(15, '\t'); // add tab characters at end
cout << s7.length() << endl; // size should now be 15

The member function empty() returns true if the string contains no characters, and is generally
faster than testing the length against a zero constant.

if (s7.empty())
cout << "string is empty" << endl;

Assignment, Append and Swap

A string variable can be assigned the value of either another string, a literal C-style character array,
or an individual character.

s1 = s2;
s2 = "a new value";
s3 = 'x';

The operator += can also be used with any of these three forms of argument, and specifies that the
value on the right hand side should be appended to the end of the current string value.

s3 += "yz"; // s3 is now xyz

The more general assign() and append() member functions let you specify a subset of the right hand
side to be assigned to or appended to the receiver. A single integer argument n indicates that only
the first n characters should be assigned/appended, while two arguments, pos and n, indicate that the
n values following position pos should be used.

s4.assign (s2, 3); // assign first three characters
s4.append (s5, 2, 3); // append characters 2, 3 and 4

The addition operator + is used to form the catenation of two strings. The + operator creates a copy
of the left argument, then appends the right argument to this value.

cout << (s2 + s3) << endl; // output catenation of s2 and s3

As with all the containers in the standard library, the contents of two strings can be exchanged using
the swap() member function.

s5.swap (s4); // exchange s4 and s5

This manual is related to the following products: