strcpy in C

Problem Statment: Given two Strings copy the contents of one string to another.

Example 1:
Input: str1="Takeuforward", str2=""
Output: str2=Takeuforward
Explanation: Contents of str1 is copied in str2

Example 2:
Input: str1="computer", str2="science"
Output: str2=computer
Explanation: Contents of str1 is copied in str2 

DisclaimerDon’t jump directly to the solution, try it out yourself first.

strcpy() is an inbuilt function in C which is used to copy contents of one string to another. It makes things easier as we don’t have to run loops and copy elements one by one.

Although, the internal implementation of the function also does the same, but we can now simply use the function instead of writing the complete code.

Syntax:

char* strcpy(char* dest, const char* src);

Parameters: It accepts two parameters “dest”, “src” where, src is the string that is to be copied and dest is the string in which the src will be copied.

Code:

C Programs

#include <stdio.h> 
#include<string.h>
int main()  
{  
    char str1[20]="take";  
    char str2[20]="uforward"; 
    strcpy(str2,str1);
    printf("After copying, the string would become: %s", str2);  
    return 0;  
}

Output:

After copying, the string would become: take

Special thanks to Subhrajit Das for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article