Open In App

Copy N Characters from One String to Another Without strncat()

In C, strings are the sequence of characters that are used to represent the textual data. Two strings can be easily concatenated or joined using the strncat() function of the C standard library up to n characters. In this article, we will learn how to concatenate the first n characters from one string to another without using the strncat() function in C.

For Example:



Input:
str1 = "Data "
str2 = "Structures"

Output:
Data Structures

Copy N Characters of One String to Another Without strncat()

To concatenate two strings without using strcat() function, we can use the concept of pointers to join each character of the two strings one by one.

Approach

C Program to Copy N Characters of One String to Another Without strncat()




// C program to illustrate how to concatenate the first n
// characters from one string to another without using the
// strncat() function in C.
#include <stdio.h>
  
void concatNChars(char* str1, char* str2, char* result,
                  int n)
{
    int i = 0, j = 0;
  
    // Copy n characters from str1 to result
    while (i < n && str1[i] != '\0') {
        result[i] = str1[i];
        i++;
    }
  
    // Copy n characters from str2 to result
    while (i < 2 * n && str2[j] != '\0') {
        result[i] = str2[j];
        i++;
        j++;
    }
  
    // Null terminate result
    result[i] = '\0';
}
  
int main()
{
    char str1[] = "Hello, ";
    char str2[] = "world!";
    char result[100];
  
    int n = 5; // Number of characters to concatenate from
               // each string
  
    concatNChars(str1, str2, result, n);
  
    printf("Concatenated string: %s\n", result);
  
    return 0;
}

Output

Concatenated string: Hello, world!

Time Complexity: O(n)
Space Complexity: O(n)


Article Tags :