MFC Programmer's SourceBook : Thinking in C++
Bruce Eckel's Thinking in C++, 2nd Ed Contents | Prev | Next

Introducing strings

While a character array can be fairly useful, it is quite limited. It’s simply a group of characters in memory, but if you want to do anything with it you must manage all the little details. For example, the size of a quoted character array is fixed at compile time. If you have a character array and you want to add some more characters to it, you’ll need to understand quite a lot (inluding dynamic memory management, character array copying and concatenation) before you can get your wish. This is exactly the kind of thing we’d like to have an object do for us.

The Standard C++ string class is designed to take care of (and hide) all the low-level manipulations of character arrays that were previously required of the C++ programmer. These manipulations have been a constant source of time-wasting and errors since the inception of the C language. So, although an entire chapter is devoted to the string class later in the book, the string is so important and it makes life so much easier that it will be introduced here and used in much of the early part of the book.

To use strings you include the C++ header file <string>. The string class is in the namespace std so a using directive is necessary. Because of operator overloading, the syntax for using strings is quite intuitive:

//: C02:HelloStrings.cpp
// The basics of the Standard C++ string class
#include <string>
#include <iostream>
using namespace std;

int main() {
  string s1, s2; // Empty strings
  string s3 = "Hello, World."; // Initialized
  string s4("I am"); // Also initialized
  s2 = "Today"; // Assigning to a string
  s1 = s3 + " " + s4; // Combining strings
  s1 += " 8 "; // Appending to a string
  cout << s1 + s2 + "!" << endl;
} ///:~ 

The first two strings, s1 and s2, start out empty, while s3 and s4 show two equivalent ways to initialize string objects from character arrays (you can as easily initialize string objects from other string objects).

You can assign to any string object using ‘ =’. This replaces the previous contents of the string with whatever is on the right-hand side, and you don’t have to worry about what happens to the previous contents – that’s handled automatically for you. To combine strings you simply use the ‘ +’ operator, which also allows you to combine character arrays with strings. If you want to append either a string or a character array to another string, you can use the operator ‘ +=’. Finally, note that iostreams already know what do do with strings, so you can just send a string (or an expression that produces a string, which happens with s1 + s2 + "!" ) directly to cout in order to print it.

Contents | Prev | Next


Go to CodeGuru.com
Contact: webmaster@codeguru.com
© Copyright 1997-1999 CodeGuru