C Program To Copy One String To Another String

In this tutorial, i am going to show you how to copy one string to another string with the help of for loop, function, recursion, and strcpy() built-in library function in c programs.

All C Programs To Copy One String To Another String

  • C Program To Copy One String To Another String using For Loop
  • C Program To Copy One String To Another String using Function
  • C Program To Copy One String To Another String using recursion
  • C Program To Copy One String To Another String using Strcyp()

C Program To Copy One String To Another String using For Loop

#include <stdio.h>
 
int main()
{
    char s1[1000],s2[1000];  
    int i;
 
    printf("Enter any string: ");
    gets(s1);
    for(i=0;s1[i]!='\0';i++)  //  or  for(i=0;s1[i];i++)
    {
    	s2[i]=s1[i];
	}
	s2[i]='\0';
 
    printf("original string s1='%s'\n",s1);
    printf("copied string   s2='%s'",s2);
 
 
    return 0;
}

The result of the above c program; as follows:

Enter any string: tutsmake
original string s1='tutsmake'
copied string   s2='tutsmake'

C Program To Copy One String To Another String using Function

#include <stdio.h>
#include <string.h>
 
void stringcopy(char *s1,char *s2)
{
	int i;
    for(i=0;s2[i]=s1[i];i++);
    
    s2[i]='\0';
    
 	
}
int main()
{
    char s1[1000],s2[1000];  
    int i;
 
    printf("Enter any string: ");
    gets(s1);
    stringcopy(s1,s2);
    
    printf("original string s1='%s'\n",s1);
    printf("copied string   s2='%s'",s2);
    return 0;
    
}

The result of the above c program; as follows:

Enter any string: hellllo
original string s1='hellllo'
copied string   s2='hellllo'

C Program To Copy One String To Another String using recursion

void stringcopy(char *s1,char *s2,int i)
{
    if(s1[i]=='\0')
    {
    	s2[i]='\0';
    	return;
	}  
	else
	{
		 s2[i]=s1[i];
         stringcopy(s1,s2,++i);
    }
}
int main()
{
    char s1[1000],s2[1000];  
    int i;
 
    printf("Enter any string: ");
    gets(s1);
    stringcopy(s1,s2,0);
     printf("original string s1='%s'\n",s1);
    printf("copied string   s2='%s'",s2);
    return 0;
}

The result of the above c program; as follows:

Enter any string: hyyyy
original string s1='hyyyy'
copied string   s2='hyyyy'

C Program To Copy One String To Another String using Strcyp()

#include <stdio.h>
#include <string.h>
 
 
int main()
{
   char s1[1000],s2[1000];  
    int i;
 
    printf("Enter any string: ");
    gets(s1);
    strcpy(s2,s1);
    printf("original string s1='%s'\n",s1);
    printf("copied string   s2='%s'",s2);
    return 0;
    
}

The result of the above c program; as follows:

Enter any string: welcome
original string s1='welcome'
copied string   s2='welcome'

Be First to Comment

Leave a Reply

Your email address will not be published.