next up previous
Next: The Standard C++ library Up: canned_classes Previous: The Standard C++ Library:

The Standard C++ library string class

Finally, we return to the string class. Like the complex 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:



#include <iostream>
#include <string>
using namespace std;

int main()
{
  string firstname,lastname,fullname;
  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[0] << "\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 of the string class:

The subscript operator is overloaded so it functions in the same way as a character array.



Carleton DeTar 2008-11-10