This is a C program to read two strings & concatenate the strings.
This program takes two strings as input and concatenate them.
1. Take two strings as input and store them in two different arrays.
2. Find the position of the last element of the first array and from that position keep on adding the elements of the second array.
3. Exit.
Here is source code of the C program to read two strings & concatenate the strings. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C program to read two strings and concatenate them, without using
* library functions. Display the concatenated string.
*/
#include <stdio.h>
#include <string.h>
void main()
{
char string1[20], string2[20];
int i, j, pos;
/* Initialize the string to NULL values */
memset(string1, 0, 20);
memset(string2, 0, 20);
printf("Enter the first string : ");
scanf("%s", string1);
printf("Enter the second string: ");
scanf("%s", string2);
printf("First string = %s\n", string1);
printf("Second string = %s\n", string2);
/* Concate the second string to the end of the first string */
for (i = 0; string1[i] != '\0'; i++)
{
/* null statement: simply traversing the string1 */
;
}
pos = i;
for (j = 0; string2[j] != '\0'; i++)
{
string1[i] = string2[j++];
}
/* set the last character of string1 to NULL */
string1[i] = '\0';
printf("Concatenated string = %s\n", string1);
}
1. Take two strings as input and store them in the arrays string1 and string2 respectively.
2. Using for loop find the position of the last element of the array string1[]. Store that position in the variable pos.
3. Using another for loop add the elements of the array string2[] into the array string1[] starting from the obtained position.
4. Print the array string1[] as output.
Enter the first string : San Enter the second string: foundry First string = San Second string = foundry Concatenated string = Sanfoundry
Sanfoundry Global Education & Learning Series – 1000 C Programs.
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
- Get Free Certificate of Merit in C Programming
- Participate in C Programming Certification Contest
- Become a Top Ranker in C Programming
- Take C Programming Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Watch Advanced C Programming Videos
- Practice BCA MCQs
- Buy Computer Science Books
- Buy C Books
- Apply for C Internship