Open In App

C Program to Concatenate Two Strings Without Using strcat

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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




// 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)



Last Updated : 19 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads