
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements