7.11. 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.

In the active code below, we use the + operator to concatenate fruit with bakedGood to create dessert.

The output of this program is banana nut bread.

Warning

Unfortunately, the + operator does not work on native C strings.

Thus, you cannot write something like

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

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

It is also possible to concatenate a character onto the beginning or end of an string. 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:

The active code below outputs the ducklings names in alphabetical order.

The output of this program is:

Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack

Again, be careful to use string concatenation only with strings 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.

As an exercise, put together the code below so that it prints ``C++ is so fun!””

Put together the code below to creater a function <code>greeter</code> that adds “hello” and “goodbye” behind and ahead of a message respectively and then prints the new message. Example: <code>greeter(“ssup”)</code> will print “hello ssup goodbye”;

You have attempted of activities on this page