
Add String in C
The concatenate (add) strings using the strcat
function from the standard library <string.h>
. However, C doesn’t have built-in support for manipulating strings as easily as some other languages like C++ or Python. Here’s a simple example of how to concatenate strings in C:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100]; // Declare the first string
char str2[100]; // Declare the second string
// Input the first string
printf("Enter the first string: ");
scanf("%s", str1);
// Input the second string
printf("Enter the second string: ");
scanf("%s", str2);
// Concatenate str2 to str1
strcat(str1, str2);
// Print the concatenated string
printf("Concatenated string: %s\n", str1);
return 0;
}
In this program:
- We declare two character arrays
str1
andstr2
, which will store the input strings. - We use
scanf
to input the first and second strings from the user. Note thatscanf
reads only one word at a time, separated by spaces. - We use the
strcat
function to concatenatestr2
to the end ofstr1
. Thestrcat
function modifiesstr1
in place and appends the characters ofstr2
to it. - Finally, we print the concatenated string.
Keep in mind that this example assumes that the input strings do not exceed the array size (100 in this case), and it doesn’t handle cases where the result of concatenation may exceed the available space in str1
. In real-world scenarios, you should perform proper error checking and allocate memory dynamically as needed.
Additionally, C also provides a safer alternative to strcat
called strncat
, which allows you to specify the maximum number of characters to concatenate to avoid buffer overflows.