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
Ouack
Pack
Quack
Again, be careful to use string concatenation only with string
s
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.
- C++ rocks
- Concatenation does not automatically add a space.
- C++
- The expression s+t is evaluated first, then the resulting string is printed.
- C++rocks
- Yes, the two strings are glued end to end.
- Error, you cannot add two strings together.
- The + operator has different meanings depending on the operands, in this case, two strings.
Q-3: What is printed by the following statements?
string s = "C++";
string t = "rocks";
cout << s + t << endl;
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 greeter
that adds “hello” and “goodbye” behind and ahead of a message
respectively and then prints the new message.
Example: greeter("ssup")
will print “hello ssup goodbye”