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 |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |