C Copy String

C Copy String


In this tutorial, we will learn about how to copy one string to another in C language, with and without using library function strcpy(). At last, we will also learn, how to copy string using pointer. Let's first start with copy string using library function.

Copy String in C using strcpy() Function

To copy string in C programming, you have to ask from user to enter the string to store it in first string variable say str1 and then copy it into the second string variable say str2 using the strcpy() function of string.h library. The function strcpy() takes two argument. The value of second argument gets copied to first argument.

#include<stdio.h>
#include<conio.h>
#include<string.h>
int main()
{
    char str1[20], str2[20];
    printf("Enter the string: ");
    gets(str1);
    printf("\nString 1 = %s", str1);
    strcpy(str2, str1);
    printf("\nString 2 = %s", str2);
    getch();
    return 0;
}

As the above program was written in Code::Blocks IDE, therefore after successful build and run, here is the first screenshot of the sample run that you will also see on your output screen after running the program:

c program copy string

Now supply any string say codescracker and press ENTER key to see the similar output as given here. This is the second snapshot of the sample run:

copy string c