Function to copy string (Iterative and Recursive)

20 Jun, 2022
Given two strings, copy one string to other using recursion. We basically need to write our own recursive version of strcpy in C/C++
Examples: 
Input : s1 = "hello"
        s2 = "geeksforgeeks"
Output : s2 = "hello"

Input :  s1 = "geeksforgeeks"
         s2 = ""
Output : s2 = "geeksforgeeks"
Iterative : Copy every character from s1 to s2 starting from index = 0 and in each call increase the index by 1 until s1 doesn’t reach to end; 
C++
Java
Python3
C#
Javascript
// Iterative CPP Program to copy one String // to another.#include <bits/stdc++.h>using namespace std; // Function to copy one string to other// assuming that other string has enough// space.void myCopy(char s1[], char s2[]){    int i = 0;    for (i=0; s1[i] != '\0'; i++)       s2[i] = s1[i];    s2[i] = '\0';} // Driver functionint main(){    char s1[100] = "GEEKSFORGEEKS";    char s2[100] = "";    myCopy(s1, s2);    cout << s2;    return 0;}
// Iterative Java Program to copy one String// to another.class GFG{     // Function to copy one string to other// assuming that other string has enough// space.static void myCopy(char s1[], char s2[]){    int i = 0;    for (i = 0; i < s1.length; i++)         s2[i] = s1[i];} // Driver codepublic static void main(String[] args){    char s1[] = "GEEKSFORGEEKS".toCharArray();    char s2[] = new char[s1.length];    myCopy(s1, s2);    System.out.println(String.valueOf(s2));}} // This code contributed by Rajput-Ji
# recursive Python Program to copy one String# to another. # Function to copy one string to otherdef copy_str(x,y):    if len(y)==0:        return x    else:        c = copy_str(x,(y)[1:-1])        return cx = input()y = input()print(copy_str(x,y)) # This code contributed by deeksha20049@iiid.ac.in#deeksha20049
// Iterative C# Program to copy one String// to another.using System; class GFG{     // Function to copy one string to other// assuming that other string has enough// space.static void myCopy(char []s1, char []s2){    int i = 0;    for (i = 0; i < s1.Length; i++)        s2[i] = s1[i];} // Driver codepublic static void Main(String[] args){    char []s1 = "GEEKSFORGEEKS".ToCharArray();    char []s2 = new char[s1.Length];    myCopy(s1, s2);    Console.WriteLine(String.Join("", s2));}} // This code is contributed by 29AjayKumar
<script> // Iterative Javascript Program to copy one String// to another.    // Function to copy one string to other// assuming that other string has enough// space.function myCopy(s1, s2){    let i = 0;    for (i = 0; i < s1.length; i++)         s2[i] = s1[i];} // Driver code    // Driver Codelet s1 = "GEEKSFORGEEKS";let s2 = [];let index = 0; myCopy(s1, s2, index); document.write(s2.join("")); // This code contributed by shivanisinghss2110 </script>
GEEKSFORGEEKS
 
Time Complexity: O(m)
Here m is the length of string s1.
Auxiliary Space: O(1)
As constant extra space is used.
Recursive : Copy every character from s1 to s2 starting from index = 0 and in each call increase the index by 1 until s1 doesn’t reach to end; 
C++
Java
Python3
C#
Javascript
// CPP Program to copy one String to// another using Recursion#include <bits/stdc++.h>using namespace std; // Function to copy one string in to other// using recursionvoid myCopy(char s1[], char s2[], int index = 0){    // copying each character from s1 to s2    s2[index] = s1[index];     // if string reach to end then stop    if (s1[index] == '\0')         return;     // increase character index by one    myCopy(s1, s2, index + 1);} // Driver functionint main(){    char s1[100] = "GEEKSFORGEEKS";    char s2[100] = "";    myCopy(s1, s2);    cout << s2;    return 0;}
// Java Program to copy one String to// another using Recursionclass GFG{         // Function to copy one string in to other    // using recursion    static void myCopy(char s1[],                       char s2[], int index)    {        // copying each character from s1 to s2        s2[index] = s1[index];         // if string reach to end then stop        if (index == s1.length - 1)        {            return;        }         // increase character index by one        myCopy(s1, s2, index + 1);    }     // Driver Code    public static void main(String[] args)    {        char s1[] = "GEEKSFORGEEKS".toCharArray();        char s2[] = new char[s1.length];        int index = 0;        myCopy(s1, s2, index);        System.out.println(String.valueOf(s2));    }} // This code is contributed by PrinciRaj1992
# recursive Python Program to copy one String# to another. # Function to copy one string to other  def copy_str(x, y):    if len(y) == 0:        return x    else:        c = copy_str(x, (y)[1:-1])        return c  x = input("hello")y = input("no")print(copy_str(x, y)) # This code contributed by deeksha20049@iiid.ac.in
// C# Program to copy one String to// another using Recursionusing System; class GFG{         // Function to copy one string in to other    // using recursion    static void myCopy(char []s1,                       char []s2, int index)    {        // copying each character from s1 to s2        s2[index] = s1[index];         // if string reach to end then stop        if (index == s1.Length - 1)        {            return;        }         // increase character index by one        myCopy(s1, s2, index + 1);    }     // Driver Code    public static void Main(String[] args)    {        char []s1 = "GEEKSFORGEEKS".ToCharArray();        char []s2 = new char[s1.Length];        int index = 0;        myCopy(s1, s2, index);        Console.WriteLine(String.Join("", s2));    }} // This code is contributed by Princi Singh
<script> // Javascript program to copy one String to// another using Recursion     // Function to copy one string in to other// using recursionfunction myCopy(s1, s2, index){         // Copying each character from s1 to s2    s2[index] = s1[index];     // If string reach to end then stop    if (index == s1.length - 1)    {        return;    }         // Increase character index by one    myCopy(s1, s2, index + 1);} // Driver Codevar s1 = "GEEKSFORGEEKS";var s2 = [];var index = 0; myCopy(s1, s2, index); document.write(s2.join("")); // This code is contributed by gauravrajput1 </script>
GEEKSFORGEEKS
 
Time Complexity: O(m)
Here m is the length of string s1.
Auxiliary Space: O(1)
As it is a tail recursive function constant extra space is used.
Function to copy string - strcpy implementation | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFunction to copy string - strcpy implementation | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=6ICIyQTAxWM" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Rajput-Ji
29AjayKumar
princiraj1992
princi singh
codingnoob2002
GauravRajput1
shivanisinghss2110
tausifsiddiqui
abhijeet19403
Recursion
Strings
Strings
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sum of the series (1*2) + (2*3) + (3*4) + ...... upto n terms
Generate all the binary strings of N bits
Traverse a given Matrix using Recursion
Generating subarrays using recursion
Practice Questions for Recursion | Set 1
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Different Methods to Reverse a String in C++
Python program to check if a string is palindrome or not