Different ways to copy a string in C/C++

Copying a string is a common operation in C/C++ used to create a duplicate copy of the original string. In this article, we will see how to copy strings in C/C++.

Methods to Copy a String in C/C++

1. Using strcpy()

Syntax

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

Example: Program to copy the string using strcpy() function

C

// C program to copy the string using // strcpy function // Function to copy the string char * copyString( char s[]) s2 = ( char *) malloc (20); strcpy (s2, s); return ( char *)s2; // Driver Code char s1[20] = "GeeksforGeeks" ; // Function Call s2 = copyString(s1); printf ( "%s" , s2);

C++

// CPP program to copy the string using // strcpy function using namespace std; // Function to copy the string char * copyString( char s[]) s2 = ( char *) malloc (20); strcpy (s2, s); return ( char *)s2; // Driver Code char s1[20] = "GeeksforGeeks" ; // Function Call s2 = copyString(s1); cout << s2 << endl; // This code is contributed by Susobhan Akhuli Output
GeeksforGeeks

Complexity Analysis

2. Using memcpy()

The memcpy() function is also used to copy from source to destination no matter what the source data contains and is defined in header and memcpy() require a size parameter to be passed.

The main difference is that memcpy() always copies the exact number of specified bytes. strcpy() and other str methods, on the other hand, will copy until it reads a NULL (‘\0’) byte, and then stop after that. strcpy() is not intended to be used with zero-terminated C-strings.

memcpy() is hardware optimized and copies faster and works with any type of source data (like binary or encrypted bytes). strcpy() should never be used unless for any specific reason, and if you know the lengths of the strings, memcpy() is a better choice.

Syntax

void *memcpy(void *to, const void *from, size_t numBytes);

Example: Program to copy the string using memcpy function