C strcat() Function

strcat() adds (concatenates) the second string at the end of the first string.

Syntax

char *strcat(char *dest, const char *src);

Example: full name

#include <stdio.h>
#include <string.h>

int main(void) {
    char full[30] = "Robin";

    strcat(full, " ");
    strcat(full, "Sharma");
    printf("%s\n", full);
    return 0;
}

Output:

Output of the above program is

Robin Sharma

The destination array (full) has space of 30 characters, so the joined text fits. It must also hold a null character at the end.

Safer: strncat

#include <stdio.h>
#include <string.h>

int main(void) {
    char text[10] = "Good";

    strncat(text, " Morning", sizeof(text) - strlen(text) - 1);
    printf("%s\n", text);
    return 0;
}

Output:

Output of the above program is

Good Morn

Only 5 more characters could fit, so ” Morn” was added.

Note: The first array must already be a valid string (with a null character) and big enough for both texts. Never use strcat() on a string literal like "Hello".

Next: C strcmp() Function.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to find the sum and average of array elements
Write a C program to find the largest element in an array
Write a C program to print the elements of an array in reverse order
Write a C program to sort an array using bubble sort
Write a C program to search an element in an array
Write a C program to add two matrices
Write a C program to find the length of a string without using strlen
Interview Questions & Answers
What is an array in C?
How is a string stored in C?
How to reverse a string in C?
What is the difference between memcpy() and strcpy() in C?