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()
We can use the inbuilt function strcpy() from <string.h> header file to copy one string to the other. strcpy() accepts a pointer to the destination array and source array as a parameter and after copying it returns a pointer to the destination string.
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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = (char*)malloc(20);
strcpy(s2, s);
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
printf("%s", s2);
return 0;
}
C++
// CPP program to copy the string using
// strcpy function
#include <bits/stdc++.h>
using namespace std;
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = (char*)malloc(20);
strcpy(s2, s);
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
cout << s2 << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
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 <string.h> 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
C
// C program to copy the string using
// memcpy function
#include <stdio.h>
#include <string.h>
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20];
// Function
memcpy(s2, s1, strlen(s1));
printf("%s\n", s2);
return 0;
}
// This code is modified by Susobhan Akhuli
C++
// CPP program to copy the string using
// memcpy function
#include <iostream>
#include <string.h>
using namespace std;
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20];
// Function
memcpy(s2, s1, strlen(s1));
cout << s2 << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
3. Using Loops
The idea is to use a for loop to copy the content of the first character array to the second character array one by one.
Example: Program to copy string using loops
C
// C program to copy string using loops
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to copy the string
char* copyString(char s[])
{
int i;
char* s2;
s2 = (char*)malloc(20);
// Executing till null character
// is found
for (i = 0; s[i] != '\0'; i++) {
// Copy the character one
// by one from s1 to s2
s2[i] = s[i];
}
// Return the pointer of newly
// created string
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
printf("%s", s2);
return 0;
}
C++
// CPP program to copy string using loops
#include <iostream>
#include <string.h>
using namespace std;
// Function to copy the string
char* copyString(char s[])
{
int i;
char* s2;
s2 = (char*)malloc(20);
// Executing till null character
// is found
for (i = 0; s[i] != '\0'; i++) {
// Copy the character one
// by one from s1 to s2
s2[i] = s[i];
}
// Return the pointer of newly
// created string
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
cout << s2 << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
4. Using Pointers
The idea is to copy the contents of the string array to another array using pointers and print the resultant string by traversing the new pointer. We run a loop until the null character '\0' is found in the source string and copy each character from the source string to the destination string using the dereferencing operator *.
Example: Program to copy the string using pointers
C
// C program to copy the string
// using pointers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Function to copy the string
char* copyString(char s[])
{
char *s2, *p1, *p2;
s2 = (char*)malloc(20);
p1 = s;
p2 = s2;
// Executing till the null
// character is found
while (*p1 != '\0') {
// Copy the content of s1 to s2
*p2 = *p1;
p1++;
p2++;
}
*p2 = '\0';
return s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
s2 = copyString(s1);
printf("%s", s2);
return 0;
}
C++
// CPP program to copy the string
// using pointers
#include <iostream>
#include <string.h>
using namespace std;
// Function to copy the string
char* copyString(char s[])
{
char *s2, *p1, *p2;
s2 = (char*)malloc(20);
p1 = s;
p2 = s2;
// Executing till the null
// character is found
while (*p1 != '\0') {
// Copy the content of s1 to s2
*p2 = *p1;
p1++;
p2++;
}
*p2 = '\0';
return s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
s2 = copyString(s1);
cout << s2 << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
5. Using Pointers and Post-Increment Operator
The idea is to use a while loop to assign the content of string array1 to string array2 one by one and increment using the post-increment operator to move to the next character. The loop continues until the null character '\0' is found.
Example: Program to copy a string using pointers and post-increment operator
C
// C program to copy the string
#include <stdio.h>
#include <stdlib.h>
// Function to copy the string
void copyString(char* t, char* s)
{
// (return ASCII value which is True,
// therefore will be in the loop
// till the condition is False
while (*t++ = *s++)
;
}
// Driver Code
int main()
{
char s2[20] = "GeeksforGeeks";
char s1[20];
// Function Call
copyString(s1, s2);
printf("%s", s1);
return 0;
}
C++
// CPP program to copy the string
#include <iostream>
using namespace std;
// Function to copy the string
void copyString(char* t, char* s)
{
// (return ASCII value which is True,
// therefore will be in the loop
// till the condition is False
while (*t++ = *s++)
;
}
// Driver Code
int main()
{
char s2[20] = "GeeksforGeeks";
char s1[20];
// Function Call
copyString(s1, s2);
cout << s2 << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
6. Using sprintf()
Instead of printing the string in the output buffer, we can store it in a specified char buffer or destination string in sprintf() to copy the string.
Syntax
int sprintf(char *source, const char *formatted_string, ...);
Example: Program to copy the string using sprintf function
C
// C program to copy the string using
// sprintf function
#include <stdio.h>
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20];
// Function
sprintf(s2, "%s", s1);
printf("%s\n", s1);
return 0;
}
C++
// CPP program to copy the string using
// sprintf function
#include <cstring>
#include <iostream>
using namespace std;
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20];
// Function
sprintf(s2, "%s", s1);
cout << s1 << endl;
return 0;
}
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
7. strncpy()
We can use the inbuilt function strncpy() from <string.h> header file to copy one string to the other. The strcnpy() function accepts a pointer to the destination array and source array as a parameter and the maximum number of characters to be copied and after copying, it returns a pointer to the destination string.
Syntax
char *strncpy ( char *destination, const char *source, size_t num );
Example: Program to copy the string using strncpy function
C
// C program to copy the string using
// strncpy function
#include <stdio.h>
#include <string.h>
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = (char*)malloc(20);
strncpy(s2, s, 20);
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
printf("%s", s2);
return 0;
}
// This code is contributed by Susobhan Akhuli
C++
// CPP program to copy the string using
// strncpy function
#include <bits/stdc++.h>
using namespace std;
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = (char*)malloc(20);
strncpy(s2, s, 20);
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
8. Using strdup()
We can use the inbuilt function strdup() from the string.h header file to duplicate a string by allocating memory for a copy of the string using malloc, and then copying the string into the newly allocated memory. The function returns a pointer to the newly allocated copy of the string.
Syntax
char *strdup(const char *s);
Example: Program to copy the string using strdup function
C
// C program to copy the string
// using strdup function
#include <stdio.h>
#include <string.h>
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = strdup(s);
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
printf("%s", s2);
return 0;
}
// This code is contributed by Susobhan Akhuli
C++
// CPP program to copy the string
// using strdup function
#include <bits/stdc++.h>
using namespace std;
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = strdup(s);
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(N)
9. Using strndup()
The strndup() function is similar to strdup(), but it can copy at most n bytes.
Syntax
char *strndup(const char *s, size_t n);
Example: Program to copy the string using strndup function
C
// C program to copy the string
// using strndup function
#include <stdio.h>
#include <string.h>
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = strndup(s, strlen(s));
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
printf("%s", s2);
return 0;
}
// This code is contributed by Susobhan Akhuli
C++
// CPP program to copy the string
// using strndup function
#include <bits/stdc++.h>
using namespace std;
// Function to copy the string
char* copyString(char s[])
{
char* s2;
s2 = strndup(s, strlen(s));
return (char*)s2;
}
// Driver Code
int main()
{
char s1[20] = "GeeksforGeeks";
char* s2;
// Function Call
s2 = copyString(s1);
cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(N)
10. Using std::string class (=) Operator
The easiest way to copy a string is to use the assignment operator (=) of the std::string class to copy the contents of one string to another.
Note: There are no inbuilt classes in C, hence '=' operator is only available in C++.
Syntax
std::string copy = original;
Example: Program to copy the string using std::string class (=) Operator
C++
// CPP program to copy the string
// using std::string class (=) Operator
#include <bits/stdc++.h>
// Function to copy the string
std::string copyString(std::string s)
{
std::string s2 = s;
return s2;
}
// Driver Code
int main()
{
std::string s1 = "GeeksforGeeks";
std::string s2;
// Function Call
s2 = copyString(s1);
std::cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(N)
11. Using std::string::assign() Method
We can use the std::string::assign() method to copy a string. This method takes a string as an argument and assigns its value to the string object on which the method is called.
Note: This method is only available in C++, not in C.
Syntax
string_object.assign(string_to_copy);
Example: Program to copy the string using std::string::assign() method
C++
// CPP program to copy the string
// using std::string::assign() method
#include <bits/stdc++.h>
// Function to copy the string
std::string copyString(std::string s)
{
std::string s2;
// std::string::assign() method
s2.assign(s);
return s2;
}
// Driver Code
int main()
{
std::string s1 = "GeeksforGeeks";
std::string s2;
// Function Call
s2 = copyString(s1);
std::cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
12. Using memmove() Function
We can use memmove() function to copy a memory block from one location to another. It is declared in <string.h> header file.
Syntax
void *memmove(void *to, const void *from, size_t numBytes);
Example: Program to copy the string using memmove() function.
C
// C program to copy the string
// using memmove() function
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20];
// Copies contents of s1 to s2
memmove(s2, s1, sizeof(s1));
printf("%s", s2);
return 0;
}
// This code is contributed by Susobhan Akhuli
C++
// CPP program to copy the string
// using memmove() function
#include <bits/stdc++.h>
using namespace std;
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20];
// Copies contents of s1 to s2
memmove(s2, s1, sizeof(s1));
cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
13. Using strcat() Function
We can use strcat() function to append a copy of the source string in the destination string and a terminating Null character. It is declared in string.h (For C) and cstring(For C++) header file.
Note: The strcat() function can be used to copy the source string to a destination string only if the destination string is empty, as the strcat function is used to concatenate one string at the end of the another string.
Syntax
char *strcat(char *dest, const char *src);
Example: Program to copy the string using strcat() function
C
// C program to copy the string
// using strcat() function
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20] = "";
// Copies contents of s1 to s2
strcat(s2, s1);
printf("%s", s2);
return 0;
}
// This code is contributed by Susobhan Akhuli
C++
// CPP program to copy the string
// using strcat() function
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20] = "";
// Copies contents of s1 to s2
strcat(s2, s1);
cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
14. Using strncat() Function
We can use strncat() function to append not more than n characters from the string pointed to by src to the end of the string pointed to by dest plus a terminating Null-character. It is declared in string.h (For C) and cstring(For C++) header file.
Note: The strcat() function can be used to copy the source string to a destination string only if the destination string is empty, as the strcat function is used to concatenate a specified number of characters from one string at the end of the another string.
Syntax
char *strncat(char *dest, const char *src, size_t n)
Example: Program to copy the string using strncat() function
C
// C program to copy the string
// using strncat() function
#include <stdio.h>
#include <string.h>
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20] = "";
// Appends 13 characters from s1 to s2
strncat(s2, s1, 13);
printf("%s", s2);
return 0;
}
// This code is contributed by Susobhan Akhuli
C++
// CPP program to copy the string
// using strncat() function
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char s1[20] = "GeeksforGeeks";
char s2[20] = "";
// Appends 13 characters from s1 to s2
strncat(s2, s1, 13);
cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
15. Using std::string::c_str()
std::string::c_str() is a member function of the C++ string class which returns a pointer to an array of characters (null-terminated) containing the same sequence of characters as the string object. The returned pointer is valid until the string object is destroyed or modified. This method is used to copy the contents of the string object into a character array, which can be used to access the contents of the string.
Syntax
const CharT* c_str() const
Example: Program to copy the string using std::string::c_str() method
C++
// CPP program to copy the string
// using std::string::c_str() method
#include <bits/stdc++.h>
// Function to copy the string
const char* copyString(string s)
{
const char* s2;
// std::string::c_str() method
s2 = s.c_str();
return s2;
}
// Driver Code
int main()
{
string s1 = "GeeksforGeeks";
string s2;
// Function Call
s2 = copyString(s1);
cout << s2;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(1)
- Auxiliary Space: O(1)
16. Using std::string::append() Method
std::string::append() is a C++ method used to copy a string into another string. It takes the string to be copied as an argument and appends it at the end of the calling string.
Note: This function is only available in C++. In C, the strcat() function can be used to copy a string into another string.
Syntax
string.append(string_to_be_copied);
Example: Program to copy the string using std::string::append() method
C++
// CPP program to copy the string
// using std::string::append() method
#include <iostream>
#include <string>
int main()
{
std::string s1 = "GeeksforGeeks";
std::string s2;
// Using append() to copy string-1 into string-2
s2.append(s1);
std::cout << s2 << std::endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
17. Using strtok() Method
The strtok() method is used in C/C++ to tokenize a string. It takes two parameters, the first is a pointer to the string to be tokenized, and the second is a pointer to a set of delimiting characters. The method then returns a pointer to the token found in the string, which can then be used to copy it.
Syntax
char *strtok(char *str, const char *delim);\
Example: Program to copy the string using strtok() method
C++
// CPP program to copy the string
// using strtok() method
#include <cstring>
#include <iostream>
using namespace std;
int main()
{
char str[] = "GeeksforGeeks GFG GEEKS";
char* token = strtok(str, " ");
// token now contains the first word in the string
char word[100];
strcpy(word, token);
// word now contains a copy of the first word in the
// string
cout << word << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Complexity Analysis
- Time Complexity: O(N)
- Auxiliary Space: O(1)
Note: In all the above methods the size of the destination array must be greater than the length of the source string to copy all the characters.
Similar Reads
Different ways to access characters in a given String in C++
String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character. There are several ways to access substrings and individual characters of a string. The string class supports the following functions for this purpose: operator[]at()subst
4 min read
Different Methods to Reverse a String in C++
Reversing the string means the last character will be the first character, second last character will be second character and so on. In C++, we can reverse a string in various different ways as show below:Table of ContentUsing reverse() FunctionUsing Reverse IteratorsUsing a StackUsing Two Pointer T
3 min read
Convert String to int in C++
Converting a string to int is one of the most frequently encountered tasks in C++. As both string and int are not in the same object hierarchy, we cannot perform implicit or explicit type casting as we can do in case of double to int or float to int conversion. Conversion is mostly done so that we c
7 min read
Convert String to size_t in C++
To convert String to size_t in C++ we will use stringstream, It associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). We must include the stream header file in order to use stringstream. When parsing input, the stringstream class comes in qu
1 min read
Difference between strncmp() and strcmp in C/C++
The basic difference between these two are : strcmp compares both the strings till null-character of either string comes whereas strncmp compares at most num characters of both strings. But if num is equal to the length of either string than strncmp behaves similar to strcmp.Problem with strcmp func
3 min read
Strings in C++ and How to Create them?
Strings in C++ are used to store text or sequences of characters. In C++ strings can be stored in one of the two following ways: C-style string (using characters)String class Each of the above methods is discussed below: 1. C style string: In C, strings are defined as an array of characters. The dif
2 min read
5 Different Methods to Find Length of a String in C++
The string is a sequence of characters or an array of characters. The declaration and definition of the string using an array of chars are similar to the declaration and definition of an array of any other data type. Examples: Input: "Geeksforgeeks" Output: 13 Input: "Geeksforgeeks \0 345" Output: 1
4 min read
Copy File To Vector in C++ STL
Prerequisite:Â Vectors in C++ STLFile Handling in C++ The C++ Standard Template Library (STL) provides several useful container classes that can be used to store and manipulate data. One of the most commonly used container classes is the vector. In this article, we will discuss how to copy the conte
2 min read
Convert given Binary Array to String in C++ with Examples
Given a binary array arr[] containing N integer elements, the task is to create a string s which contains all N elements at the same indices as they were in array arr[]. Example: Input: arr[] = {0, 1, 0, 1}Output: string = "0101" Input: arr[] = { 1, 1, 0, 0, 1, 1}Output: string = "110011" Different
6 min read
How to print or output a String?
In this article, we are going to learn how to print or output a string using different languages. Strings are considered a data type in general and are typically represented as arrays of bytes (or words) that store a sequence of characters. Strings are defined as an array of characters. Topics: Lang
3 min read