Concatenating n characters from source string to destination string in C


Problem

Write a C program to concatenate n characters from source string to destination string using strncat library function

Solution

The strcat function

  • This function is used for combining or concatenating two strings.

  • The length of the destination string must be greater than the source string.

  • The resultant concatenated string will be in the source string.

Syntax

strcat (Destination String, Source string);

Example 1

#include <string.h>
main(){
   char a[50] = "Hello";
   char b[20] = "Good Morning";
   clrscr ( );
   strcat (a,b);
   printf("concatenated string = %s", a);
   getch ( );
}

Output

Concatenated string = Hello Good Morning

The strncat function

  • This function is used for combining or concatenating n characters of one string into another.

  • The length of the destination string must be greater than the source string.

  • The resultant concatenated string will be in the destination string.

Syntax

strncat (Destination String, Source string,n);

Example 2

#include <string.h>
main ( ){
   char a [30] = "Hello";
   char b [20] = "Good Morning";
   clrscr ( );
   strncat (a,b,4);
   a [9] = ‘\0’;
   printf("concatenated string = %s", a);
   getch ( );
}

Output

Concatenated string = Hello Good.

Example 3

#include<stdio.h>
#include<string.h>
void main(){
   //Declaring source and destination strings//
   char source[45],destination[50];
   //Reading source string and destination string from user//
   printf("Enter the source string :");
   gets(source);
   printf("Enter the destination string before :");
   gets(destination);
   //Concatenate all the above results//
   destination[2]='\0';
   strncat(destination,source,2);
   strncat(destination,&source[4],1);
   //Printing destination string//
   printf("The modified destination string :");
   puts(destination);
}

Output

Enter the source string :TutorialPoint
Enter the destination string before :C Programming
The modified destination string :C Tur

Updated on: 06-Mar-2021

627 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements