Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Copying one string to another string

1) Using library function strcpy()

The strcpy() function copies one string to another string.

Syntax

char *strcpy(char *destination, const char *source);

For Example

C Programming Language String Copy using strcpy() FunctionExample

#include<stdio.h>
#include<string.h>
int main()
{
    char str1[10] = "JOHN";
    char str2[10];
    strcpy(str2,str1);
    printf("\n String 1 = %s",str1);
    printf("\n String 2 = %s",str2);
    return 0;
}

Output

String 1 = JOHN
String 2 = JOHN

b) Without using a library function

Example

#include <stdio.h>
int main()
{
    int x=0;
    char name1[15]="JOHN SMITH";
    char name2[15];
	
    name2[x]=name1[x];
    while(name2[x]!='\0')
    {
        x++;
        name2[x]=name1[x];
    }
 
    printf("\n Name 1 = %s",name1);
    printf("\n Name 2 = %s",name2);
    return 0;
}

Output

Name 1 = JOHN SMITH
Name 2 = JOHN SMITH

 

Leave a reply