C Program to Concatenate Two Strings Without Using strcat
In C, concatenating two strings means combining two strings to form one string. In this article, we will learn how to concatenate two strings without using the strcat() function in C.
For Example,
Input:
str1= "Hello,"
str2= "Geek!"
Output:
Concatenated String: Hello, Geek!
Concatenating Two Strings in C
To concatenate two strings without using the strcat() function in C, we need to manually append the characters from the second string to the end of the first string using the following steps:
Approach
- First, ensure the first string has enough space to hold all characters of the second string (i.e. the size of the first string is the sum of the sizes of both strings).
- Iterate the first string and find the end where a null-terminator is encountered.
- Now, copy the second string to the first string starting from the found position.
- Finally, add a null terminator at the end of the concatenated string.
C Program to Concatenate Two Strings without using strcat()
The below example demonstrates how we can concatenate two strings without using strcat in C.
C
#include <stdio.h>
void concatenateStrings( char * str1, const char * str2)
{
while (*str1) {
++str1;
}
while (*str2) {
*str1++ = *str2++;
}
*str1 = '\0' ;
}
int main()
{
char string1[50] = "Hello, " ;
char string2[] = "Geek!" ;
concatenateStrings(string1, string2);
printf ( "Concatenated String: %s\n" , string1);
return 0;
}
|
Output
Concatenated String: Hello, Geek!
Time Complexity: O(n + m), where n is the length of the first string and m is the length of the second string.
Auxiliary Space: O(1)
Last Updated :
19 Feb, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...