7.11. String concatenation¶
+ 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
bakedGood to create
The output of this program is
banana nut bread.
+ 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
string, though, C++ will automatically convert the other.
It is also possible to concatenate a character onto the beginning or end
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
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.
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”;