Using strcat()
Part of the Logic & Flow section of Coddy's C journey — lesson 17 of 63.
You've learned how to copy strings with strcpy(), but what if you want to join two strings together? This is called concatenation, and C provides the strcat() function from the <string.h> library for this purpose.
The strcat() function appends the contents of one string to the end of another string. It takes two arguments: the destination string (which will be modified) and the source string (which will be added to the end).
#include <stdio.h>
#include <string.h>
char greeting[20] = "Hello";
char name[] = " World";
strcat(greeting, name); // greeting now contains "Hello World"It's crucial that your destination string has enough space to hold both the original content and the new content being appended. The strcat() function finds the null terminator in the destination string, removes it, copies the source string to that location, and adds a new null terminator at the very end.
This function is essential for building longer strings from smaller pieces, such as creating full sentences from individual words or combining user input with predefined text.
Sometimes you need to convert a number into a string before you can concatenate it. For this, you can use sprintf() from <stdio.h> (which is already included in most C programs). sprintf() works just like printf(), but instead of printing to the screen it writes the formatted result into a char array.
For example, to convert an integer to a string:
int age = 25;
char ageStr[10];
sprintf(ageStr, "%d", age); // ageStr now contains "25"
char result[30] = "Age: ";
strcat(result, ageStr); // result now contains "Age: 25"The first argument to
sprintf() is the destination char array, the second is the format string (using the same format specifiers as printf()), and the remaining arguments are the values to insert.Challenge
EasyWrite a C program that demonstrates string concatenation using the strcat() function to build personalized messages. Your program should:
- Read an integer
nrepresenting the number of people to process - For each person:
- Read their first name from input
- Read their last name from input
- Create a character array named
fullNamewith 100 elements - Use
strcpy()to copy the first name intofullName - Use
strcat()to append a single space " " tofullName - Use
strcat()to append the last name tofullName - Create a character array named
greetingwith 150 elements - Use
strcpy()to copy "Hello, " intogreeting - Use
strcat()to append thefullNametogreeting - Use
strcat()to append "! Welcome to our program." togreeting - Print the final greeting message
- After processing all people, create a summary message:
- Create a character array named
summarywith 100 elements - Use
strcpy()to copy "Total people processed: " intosummary - Convert the number
nto a string and usestrcat()to append it tosummary - Print the summary message
- Create a character array named
Remember to include the <string.h> header to use the string functions.
Your output should display the results in the following format:
Hello, [FirstName LastName]! Welcome to our program.
Hello, [FirstName LastName]! Welcome to our program.
...
Total people processed: [n]For example, if the input is:
2
John
Doe
Alice
SmithYour output should be:
Hello, John Doe! Welcome to our program.
Hello, Alice Smith! Welcome to our program.
Total people processed: 2This challenge tests your understanding of using strcat() to concatenate multiple strings together, combining it with strcpy() for initial string setup, and building complex strings from multiple components step by step.
Cheat sheet
The strcat() function from <string.h> concatenates (joins) two strings by appending the source string to the end of the destination string.
Syntax: strcat(destination, source)
#include <stdio.h>
#include <string.h>
char greeting[20] = "Hello";
char name[] = " World";
strcat(greeting, name); // greeting now contains "Hello World"Important: The destination string must have enough space to hold both the original content and the appended content. The function finds the null terminator in the destination, removes it, copies the source string to that location, and adds a new null terminator at the end.
The sprintf() function from <stdio.h> works like printf(), but writes the formatted result into a char array (string) instead of printing it. This makes it useful for converting integers (or other values) into strings.
Syntax: sprintf(destination, format, value)
#include <stdio.h>
int num = 42;
char numStr[10];
sprintf(numStr, "%d", num); // numStr now contains "42"Important: The destination array must be large enough to hold the resulting string, including the null terminator.
Try it yourself
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
// Read the number of people
int n;
scanf("%d", &n);
// TODO: Write your code below
// Process each person and create greeting messages
// Then create and display the summary message
return 0;
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Pointers Fundamentals
What is a Pointer?Declaring PointersThe Address-Of Operator (&)The Dereference Operator (*)NULL PointersRecap: Pointer Basics4Project: Simple Text Utility
Project OverviewCounting Characters2Pointers and Arrays
Array Names as PointersArray Elements - PointersPointer ArithmeticComparing PointersRecap: Pointer Array Traversal5Pointers and Functions
Pass-by-ValuePassing Pointers to FunctionsModifying Vars via PointersA Classic Example: SwapPassing Arrays to FunctionsRecap: Function Pointer Args8Structs and Pointers
Pointers to StructsThe Arrow Operator (->)Passing Structs by ValuePassing Struct PointersDynamic Allocation of StructsRecap: Modifying Struct - Ptr11Final Recap Challenges
Recap: Dynamic String ConcatRecap: Array of StructsRecap: Word Frequency Counter3Character Arrays and Strings
Strings as char ArraysThe Null TerminatorString Input with scanfUsing strlen()Using strcpy()Using strcat()Using strcmp()Recap: Basic String Functions