String Concatenation the process of combining two or more strings into a single string, is a fundamental operation in programming. In C language where there is no dedicated data type for string is available, string concatenation involves manipulating charactyer arrays. In this article, we will see various operations available for string concatenation in C.
Table of Contents
String Concatenation by using strcat()
The standard library(string.h) in C provides the strcat function with appends the content of one string to another. It takes two arguments- The destination string and the source string while strcat is convenient, caution is advised as it assumes sufficient space in the destination string and lacks bound checking.
#include <stdio.h>
#include <string.h>
void main()
{
char destination[] = "Gang for code";
char source[] = "code";
strcat(destination, source);
printf("concatinated string = %s", destination);
}
Output
String Concatenation by using strncat()
To address the potential risk of buffer overflow the strncat function can be employed. Thisb function requires an additional argumnet specifing the maximum number of characters to be concatenate. This ensure that concatenate does not exced the vailable space in the destination array.
#include <stdio.h>
#include <string.h>
void main()
{
char destination[] = "Gang for code";
char source[] = "code";
strncat(destination, source, 2);
printf("concatinated string = %s", destination);
}
Output
String Concatenation by using sprintf()
For more control over concatenation process the sprintf function can be employed.
#include <stdio.h>
#include <string.h>
void main()
{
char destination[] = "Gang for code";
char source[] = "code";
sprintf(destination + strlen(destination), "%s", source);
printf("concatinated string = %s", destination);
}
Output
String Concatenation in C offers multiple approaches, each with its advantage and considerations.
Happy Coding
4 thoughts on “String Concatenation in C”