The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details.


String Concatenation

Interestingly, the + operator can be used on strings; it performs string concatenation. To concatenate means to join the two operands end to end. For example:

  pstring fruit = "banana";
  pstring bakedGood = " nut bread";
  pstring dessert = fruit + bakedGood;
  cout << dessert << endl;

The output of this program is banana nut bread.

Unfortunately, the + operator does not work on native C strings, so you cannot write something like

  pstring dessert = "banana" + " nut bread";

because both operands are C strings. As long as one of the operands is an pstring, though, C++ will automatically convert the other.

It is also possible to concatenate a character onto the beginning or end of an pstring. In the following example, we will use concatenation and character arithmetic to output an abecedarian series.

"Abecedarian" refers to a series or list in which the elements appear in alphabetical order. For example, in Robert McCloskey's book Make Way for Ducklings, the names of the ducklings are Jack, Kack, Lack, Mack, Nack, Ouack, Pack and Quack. Here is a loop that outputs these names in order:

  pstring suffix = "ack";

  char letter = 'J';
  while (letter <= 'Q') {
    cout << letter + suffix << endl;
    letter++;
  }

The output of this program is:

Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

Of course, that's not quite right because I've misspelled "Ouack" and "Quack." As an exercise, modify the program to correct this error.

Again, be careful to use string concatenation only with pstrings and not with native C strings. Unfortunately, an expression like letter + "ack" is syntactically legal in C++, although it produces a very strange result, at least in my development environment.


Last Update: 2005-12-05