Open In App

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

Last Updated : 26 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Declare and initialize two integer variables, i and j, to 0. These will serve as counters in the upcoming loops.
  • Use a while loop to copy the characters from str1 to result. Continue this loop until you encounter the null character at the end of str1.
  • Use a similar while loop to copy the characters from str2 to result up to n characters. Start from where the previous loop left off.
  • After both strings have been copied, manually append the null character to the end of result.

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

C




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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads