C Program to copy string

Simple C program to copy string: There is a function in <string.h> library to copy one string into another and which is strcpy(). You can directly copy one string into another string using this function. You can copy one by one element from one string to another.
 
/* C program to copy string */
#include<stdio.h>
#include<string.h>
int main()
{
 char str[20];
 char str1[20];
 printf("Enter a string: ");
 gets(str);
 strcpy(str1,str);
 printf("str string: %s",str);
 printf("\nstr1 string: %s",str1);
 return 0;
}
/* End of the program */
  

C program to copy string by copying elements one by one
 
/* C program to copy string */
#include<stdio.h>
#include<string.h>
int main()
{
 char str[20];
 char str1[20];
 int i,n;
 printf("Enter a string: ");
 gets(str);
 n=strlen(str);
 for(i=0;i<n;i++)
 {
  str1[i]=str[i];
 }
 str1[i]='\0';
 printf("str string: %s",str);
 printf("\nstr1 string: %s",str1);
 return 0;
}
/* End of the program */
 
Another C program using null character
 
/* C program to copy string */
#include<stdio.h>
#include<string.h>
int main()
{
 char str[20];
 char str1[20];
 int i;
 printf("Enter a string: ");
 gets(str);
 for(i=0;*(str+i);i++)
 {
  str1[i]=str[i];
 }
 str1[i]='\0';
 printf("str string: %s",str);
 printf("\nstr1 string: %s",str1);
 return 0;
}
/* End of the program */






Popular posts from this blog