C Program to Concatenate Two Strings
In this article, you’ll learn to easily concatenate two strings without using the standard library function strcat().
You can concatenate two strings easily using the standard library function strcat() but, this program concatenates two strings manually without using strcat()
the function.
Example: Concatenate Two Strings Without Using strcat()
#include <stdio.h>
int main()
{
char s1[100], s2[100], i, j;
printf("Enter first string: ");
scanf("%s", s1);
printf("Enter second string: ");
scanf("%s", s2);
// calculate the length of string s1
// and store it in i
for(i = 0; s1[i] != '\0'; ++i);
for(j = 0; s2[j] != '\0'; ++j, ++i)
{
s1[i] = s2[j];
}
s1[i] = '\0';
printf("After concatenation: %s", s1);
return 0;
}
Output
Enter first string: lol Enter second string: :) After concatenation: lol:)
C program to concatenate two strings:
#include <stdio.h>
int main() {
char str1[100], str2[100], result[200];
int i, j;
printf("Enter the first string:\n");
gets(str1);
printf("Enter the second string:\n");
gets(str2);
i = 0;
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
j = 0;
while (str2[j] != '\0') {
result[i] = str2[j];
i++;
j++;
}
result[i] = '\0';
printf("Concatenated string: %s\n", result);
return 0;
}
Explanation:
#include <stdio.h>
includes the standard input-output header file in our program.char str1[100], str2[100], result[200];
declares three-character arraysstr1
,str2
andresult
to store the two input strings and the concatenated string respectively.int i, j;
declares two integer variablesi
andj
.- The
printf()
statements are used to prompt the user to input the two strings and thegets()
the function is used to input the strings. - The first
while
loop starting fromwhile (str1[i] != '\0')
copies each character of the first stringstr1
to the result stringresult
until the end of the string is reached. - The second
while
loop starting fromwhile (str2[j] != '\0')
copies each character of the second stringstr2
to the result stringresult
starting from the position after the end of the first string until the end of the second string is reached. - The statement
result[i] = '\0';
adds the null character at the end of the concatenated string to indicate the end of the string. - The last
printf()
the statement displays the concatenated string.
When we compile and run this program, it will prompt the user to input two strings and then concatenate them. Finally, it will display the concatenated string.