String concatenation
- C course
- Intermediate
- Lesson 19/116
- 5 min
Learn to concatenate strings with strcat and sprintf.
Concatenation with strcat
strcat(dest, src) appends the src string to the end of dest. dest must be large enough; otherwise a buffer overflow occurs.
Example: char dest[20] = "Merhaba"; strcat(dest, " dünya");. Here dest is a 20-byte array; strcat appends " dünya". Result: "Merhaba dünya". dest cannot be a string literal; strcat modifies it. So use a writable array like char dest[20].
Formatted concatenation with sprintf
sprintf works like printf but writes the output into a string instead of the screen. It's ideal for joining several pieces at once.
Example: char buf[30]; sprintf(buf, "%s %s", "Merhaba", "dünya");. This joins two strings with a space between. sprintf is powerful but dangerous: it doesn't check the output size. That's why modern C prefers snprintf; you'll see it in the safety lesson. For now, learning sprintf for formatted joins is enough.
Practice Concatenate two strings
Declare a writable array char dest[20] = "Merhaba";. Append the second string with strcat(dest, " dünya");. Print with printf("%s\n", dest);. Include <string.h>.
Starter code
#include <stdio.h>
#include <string.h>
// Declare a 20-byte dest array, init with "Merhaba"
// Append " dünya" with strcat
// Print with printf
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <string.h>
int main(void) {
char dest[20] = "Merhaba";
strcat(dest, " dünya");
printf("%s\n", dest);
return 0;
}Expected output
Merhaba dünya
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the concatenation tools
| Term | Meaning |
|---|---|
strcat(dest, src) |
Append |
sprintf(dest, fmt, ...) |
Formatted write |
strcpy(dest, src) |
Copy |
strlen(s) |
Measure length |
2 Which string does strcat modify?
- Only src
- Both
- Only dest Correct answer
- Neither
Explanation: strcat appends src to dest; only dest changes.
3 Complete the strcat call
char dest[20] = "Merhaba";
____(dest, " dünya");
char dest[20] = "Merhaba";
strcat(dest, " dünya");
Explanation: strcat appends the second string to the first.