C Program to Concatenate two String
Objective
Write a C program to concatenate (join) two strings manually.
Algorithm / Approach
- Read two strings:
a(the base string) andb(the string to append). - Run a loop to find the end of the first string:
while(a[i] != '\0') i++;. - Run a second loop to copy characters from
bintoastarting at indexi. - After copying, append the null terminator:
a[i] = '\0'.
main.c
#include<stdio.h>
int main( ) {
char a[100],b[100];
int i=0, j=0;
printf("Enter 1st String : ");
gets(a);
printf("Enter 2nd String : ");
gets(b);
while(a[i] != '\0') {
i++;
}
while(b[j] != '\0') {
a[i]= b[j];
i++;
j++;
}
a[i] = '\0';
i=0;
printf("After Concat : ");
while(a[i] !='\0') {
printf("%c",a[i]);
i++;
}
return 0;
}
Expected Output
Enter 1st String : C Programming Enter 2nd String : Prowess After Concat : C ProgrammingProwess
Explanation of the Program
- Concatenation is the process of appending one string to the tail end of another string (mimicking the built-in
strcat()function). - To do this, we first must find the exact memory index where the first string ends. We then start writing the second string's characters directly over the top of the first string's null terminator, expanding its length.
Complexity
Time Complexity
O(n + m) - Where n is the length of first string and m is the length of the second.
Space Complexity
O(1) - Assuming the first array has enough capacity.