C Program to accept two strings and concatenate them i.e.The second string is appended to the end of the first string

by Nideesh C on April 12, 2011 · 0 comments

in C Programming




/* C Program to accept two strings and concatenate them i.e.The second string is appended to the end of the first string */

#include <stdio.h>
#include <string.h>

void main()
{
char string1[20], string2[20];
int i,j,pos;

strset(string1, ‘\0′); /*set all occurrences in two strings to NULL*/
strset(string2,’\0′);

printf(“Enter the first string :”);
gets(string1);
fflush(stdin);

printf(“Enter the second string:”);
gets(string2);

printf(“First string  = %s\n”, string1);
printf(“Second string = %s\n”, string2);

/*To concatenate the second string to the end of the string
traverse the first to its end and attach the second string*/

for (i=0; string1[i] != ‘\0′; i++)
{
;      /*null statement: simply traversing the string1*/
}

pos = i;

for (i=pos,j=0; string2[j]!=’\0′; i++)
{
string1[i] = string2[j++];
}

string1[i]=’\0′;   /*set the last character of string1 to NULL*/

printf(“Concatenated string = %s\n”, string1);
}

/*—————————————
Output
Enter the first string :CD-
Enter the second string:ROM
First string  = CD-
Second string = ROM
Concatenated string = CD-ROM
—————————————-*/

Not Satisfied ? Just search & get the result

Related Posts Plugin for WordPress, Blogger...
Be Sociable, Share!

Related posts:

  1. C program to read two strings and concatenate them (without using library functions). Output the concatenated string along with the given string
  2. C Program to accepts two strings and compare them. Finally it prints whether both are equal, or first string is greater than the second or the first string is less than the second string
  3. C program to read a string and check whether it is a palindrome or not (without using library functions). Output the given string along with suitable message.
  4. C program to accept a string and a substring and check if the substring is present in the given string
  5. C program to insert a particular element in a specified position in a given array

Leave a Comment

Previous post:

Next post: