Open In App

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

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 program to Concatenate two string without using
// concat()
#include <stdio.h>
  
// Function to concatenate two strings
void concatenateStrings(char* str1, const char* str2)
{
    // Navigate to the end of the first string
    while (*str1) {
        ++str1;
    }
  
    // Copy characters of the second string to the end of
    // the first string
    while (*str2) {
        *str1++ = *str2++;
    }
  
    // Add the null-terminating character
    *str1 = '\0';
}
  
int main()
{
    char string1[50] = "Hello, ";
    char string2[] = "Geek!";
  
    // calling function to concatenate strings
    concatenateStrings(string1, string2);
  
    // Output the concatenated string
    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)


Article Tags :