Next: The Standard C++ library
Previous: The Standard C++ Library:
Finally, we return to the string class. Like the
class, this class comes with practically every C++ compiler. It makes
it far more convenient to manipulate strings without having to fuss
about their lengths. Here is an example of its use:
using namespace std;
char praise = " the Magnificent";
cout << "enter first name: \n";
cin >> firstname;
cout << "enter last name: \n";
cin >> lastname;
fullname = firstname + " " + lastname + praise;
cout << "Your full name is " + fullname + "\n";
cout << "It has " << fullname.size() << " characters\n";
cout << "The first character is " << fullname << "\n";
As we have noted before, this class does not need a length when a
string is declared. The length is adjusted dynamically during use.
Notice that the addition operator has been overloaded to signify
concatenation, and it accepts combinations of string objects,
character arrays and string constants. Here are some useful methods
The subscript operator is overloaded so it functions in the same way
as a character array.
empty() returns true if the string is empty.
size() returns the size of the string.
c_str() returns a pointer to the first character
in the string.