In this tutorial you will learn about the C Program to Copy String and its application with practical example.
C Program to Copy String
In this tutorial, we will learn to create a C program that will Copy String in C programming.
Prerequisites
Before starting with this tutorial, we assume that you are the best aware of the following C programming topics:
- Operators in C Programming.
- Basic Input and Output function in C Programming.
- Basic C programming.
- Using Strings in C Programming.
What is a string?
As we all know, the string is a collection of characters, symbols, digits, and blank spaces. In strings, only one variable is declared which can store multiple values.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Add a string to the variable 3. Copy from the taken variable. 4. Printing the result string. 5. End |
Program to Copy String
First, will take the input string from the user. And then will copy the string. The C programming language has many pre-defined functions for string manipulation. In today’s tutorial, we will do copy work with the help of a strcpy() function. It is used for copying the string from one variable to another variable.
With the help of the below program, we can Copy String.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include <stdio.h> #include <string.h> int main() { /* Declaring the variable for the program required to complete the operation */ char var1[1000], var2[1000]; /* Taking the input string from the user for the program */ printf("Input a string\n"); gets(var1); /* Copying the string with the help of a predefined function strcpy */ strcpy(var2, var1); /* Printing the string to the user in output */ printf("var1 string: %s\n", var1); printf("var2 string: %s\n", var2); return 0; } |
Output:-
In the above program, we have first initialized the required variable.
- var1 = it will hold the string value.
- var2 = it will hold the string value.
Taking input string from the user for copying the string.
Copying the string with the help of the assignment operator.
Printing the output copied string1 and string2.