Open In App

C Program to Concatenate Two Strings Using a Pointer

In C, concatenation of strings is nothing but it is the process of combining two strings to form a single string. If there are two strings, then the second string is added at the end of the first string. In this article, we are going to learn how to concatenate two strings using a pointer in C.

Example:



Input:
str1 = "Hello";
str2 = " GeeksforGeeks!";

Output:
Hello GeeksforGeeks

Concatenate Two Strings Using a Pointer in C

To concatenate two strings using a pointer in C, follow the below steps:

Note: Make sure that the first string contains enough space to add the second string.



C Program to Concatenate Two Strings Using a Pointer




// C Program to Concatenate Two Strings Using a Pointer
#include <stdio.h>
  
void concatenateStrings(char* str1, const char* str2)
{
    // Find the end of the first string
    while (*str1 != '\0') {
        str1++;
    }
  
    // Copy characters from the second string to the end of
    // the first string
    while (*str2 != '\0') {
        *str1 = *str2;
        str1++;
        str2++;
    }
  
    // Ensure the resulting string is null-terminated
    *str1 = '\0';
}
  
// Driver Code
int main()
{
    char str1[50] = "Hello";
    const char str2[] = " GeeksforGeeks!";
  
    concatenateStrings(str1, str2);
  
    printf("Concatenated String: %s\n", str1);
  
    return 0;
}

Output
Concatenated String: Hello GeeksforGeeks!

Time Complexity: O(N + M), where N and M is the length of the first and second string.
Space Complexity: O(1)


Article Tags :