Programming Tutorials

Write a Program in C to Copy a String to Another.

Google+ Pinterest LinkedIn Tumblr

Here is a program in C to copy one string to another string using user defined function. Here two character arrays are defined then prompted to enter the strings and copied to the first string using while() function.

Program in C to Copy a String to Another

Program in C to Copy a String to Another

Steps:

  1. At first  declare two strings str1 and str2 and integers m, i, flag and j under main function.
  2. Prompt message to enter the strings and allow to enter strings using gets() function.
  3. Prompt the message and allow to enter the index where you want to insert in the first string.
  4. Copy second string to the first string using while() function.
  5. Print the first string to the screen.

Code:

#include <stdio.h>
#include <conio.h>

void main()
{
 char str1[20], str2[20];
 int m,i,flag=0,j;

 clrscr();

 printf("Enter the 1st String");
 gets(str1);
 printf("Enter the 2nd String");
 gets(str2);

 printf("Enter the index after which you want to insert 2nd string in 1st :");
 scanf("%d", &m);
 i=0;

 while (i<=m)
 {
 i++;
 }
 j=0;

 while (str2[j]!='')
 {
  str1[i]=str2[j];
  i++;
  j++;
  if (str1[i]=='')
  flag=1;
 }

 if (flag==1)
  str1[i]='';
  printf("%s", str1); 
                getch();
} 

Shuseel Baral is a web programmer and the founder of InfoTechSite has over 5 years of experience in software development, internet, SEO, blogging and marketing digital products and services is passionate about exceeding your expectations.

Write A Comment