C program to copy one string to another

C program to copy one string to another :

In this C programming tutorial , we will learn how to copy a string using a built-in library function. The library function we are going to use is char *strcpy(char *dest, const char *src) . We will pass two variables to this function : dest and src. All the contents of src will be copied to dest. Let’s take a look into the program first :

C program to copy a string :

#include <stdio.h>
#include <stdlib.h>

int main()
{
    //1
    char firstString[100], secondString[100];

    //2
    printf("Enter a string to copy : ");

    //3
    scanf("%[^\n]s", firstString);

    //4
    strcpy(secondString, firstString);

    //5
    printf("Copied string : ");
    printf("%s", secondString);

    return 0;
}

Explanation :

The commented numbers in the above program denotes the step number below :

  1. Create two char array to hold the user input string and copied string : firstString and secondString.
  2. Ask the user to enter a string.
  3. Read the string and store it in firstString.
  4. Now, copy the string of firstString to variable secondString using strcpy function. Remember to add #include on top of the program. strcpy function is defined inside this .h file. So, if we will not add this include statement, it will not run.
  5. String is copied to the variable secondString. Print out the result .

Sample Output :

Enter a string to copy : Hello World !!
Copied string : Hello World !!

Enter a string to copy : 12345678910
Copied string : 12345678910

Enter a string to copy : !@#$%^&  *()_+
Copied string : !@#$%^&  *()_+