8.9 Concatenating Strings
Concatenating or appending strings is not as simple in C as it is in Python. To append one string to the end of a second string, you must use the strcat function.
|
The String Concatenation Function
string.h
char[] strcat(char dest[], char src[]);
The function takes two string arrays (i.e. a character array that contains a string) and appends the
src string to the dest string. The destination must be large enough to store the entire resulting string, which is comprised of the original string in dest and the string ing src. |
Consider the array declarations
- char name[35] = "John";
and suppose we want to append the last name Smith to the name string. This can be done with the function call
- strcat(name, "Smith");
which appends the entire string "Smith" to the end of the destination string as illustrated below
You will notice that the null character at the end of the string "John" is replaced with the first character of the source string and a null character is appended at the end of the new string.

The function call above does not leave a blank space between the first and last name. To include the blank space, you must include it as part of the literal string that is being appended or use a second strcat function call:
- strcat(name, " "); // first append a black space to name.
- strcat(name, "Smith"); // then append the last name.
which results in
Suppose you are given two string arrays
each of which contains a valid string and you are tasked with building a new string that contains the individual's full name. How would you complete this task? In Python, it would be accomplished with the simple statement
In C, this would require the use of a third array (
A complete sample program that solves this task is provided below. |
Program: buildname.cc
|
Consider the buildname.py example program above. What would be result if we changed the code segment that builds the full name to the following:
- strcat(fullName, firstName);
- strcat(fullName, " ");
- strcat(fullName, lastName);

