The Wayback Machine - https://web.archive.org/web/20240623194440/https://www.geeksforgeeks.org/function-copy-string-iterative-recursive/
Open In App

Function to copy string (Iterative and Recursive)

Last Updated : 07 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given two strings, copy one string to another 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; 

Implementation:

C++




// 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 function
int main()
{
    char s1[100] = "GEEKSFORGEEKS";
    char s2[100] = "";
    myCopy(s1, s2);
    cout << s2;
    return 0;
}


Java




// 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 code
public 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


Python3




## Iterative Python Program to copy one String
# to another.
# Function to copy one string to other
def myCopy(s1,s2):
    # traversing the string s1 from start to end
    for i in range(len(s1)):
        # copying value one by one
        s2[i]=s1[i]
    return "".join(s2)
 
#Driver code
s1=list("GEEKSFORGEEKS")
s2=[""]*len(s1)
print(myCopy(s1,s2))
'''Code is contributed by RAJAT KUMAR (rajatkumargla19)'''


C#




// 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 code
public 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


Javascript




<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 Code
let s1 = "GEEKSFORGEEKS";
let s2 = [];
let index = 0;
 
myCopy(s1, s2, index);
 
document.write(s2.join(""));
 
// This code contributed by shivanisinghss2110
 
</script>


Output

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; 

Implementation:

C++




// 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 recursion
void 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 function
int main()
{
    char s1[100] = "GEEKSFORGEEKS";
    char s2[100] = "";
    myCopy(s1, s2);
    cout << s2;
    return 0;
}


Java




// Java Program to copy one String to
// another using Recursion
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);
        System.out.println(String.valueOf(s2));
    }
}
 
// This code is contributed by PrinciRaj1992


Python3




# 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#




// C# Program to copy one String to
// another using Recursion
using 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


Javascript




<script>
 
// Javascript program to copy one String to
// another using Recursion    
 
// Function to copy one string in to other
// using recursion
function 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 Code
var s1 = "GEEKSFORGEEKS";
var s2 = [];
var index = 0;
 
myCopy(s1, s2, index);
 
document.write(s2.join(""));
 
// This code is contributed by gauravrajput1
 
</script>


Output: 

GEEKSFORGEEKS

 

Time Complexity: O(m), Here m is the length of string s1.
Auxiliary Space: O(m), due to recursive call stack



Similar Reads

Count consonants in a string (Iterative and recursive methods)
Given a string, count total number of consonants in it. A consonant is an English alphabet character that is not vowel (a, e, i, o and u). Examples of constants are b, c, d, f, and g. Examples : Input : abc de Output : 3 There are three consonants b, c and d. Input : geeksforgeeks portal Output : 12 1. Iterative Method C/C++ Code // Iterative CPP p
7 min read
First uppercase letter in a string (Iterative and Recursive)
Given a string find its first uppercase letterExamples : Input : geeksforgeeKs Output : K Input : geekS Output : S Method 1: linear search Using linear search, find the first character which is capital C/C++ Code // C++ program to find the first // uppercase letter using linear search #include &lt;bits/stdc++.h&gt; using namespace std; // Function
6 min read
Program to count vowels in a string (Iterative and Recursive)
Given a string, count the total number of vowels (a, e, i, o, u) in it. There are two methods to count total number of vowels in a string. Iterative Recursive Examples: Input : abc de Output : 2 Input : geeksforgeeks portal Output : 7Recommended PracticeVowel or NotTry It! 1. Iterative Method: Below is the implementation: C/C++ Code // C++ program
7 min read
Check if linked list is sorted (Iterative and Recursive)
Given a Linked List, task is to check whether the Linked List is sorted in Descending order or not? Examples : Input : 8 -&gt; 7 -&gt; 5 -&gt; 2 -&gt; 1 Output : Yes Explanation : In given linked list, starting from head, 8 &gt; 7 &gt; 5 &gt; 2 &gt; 1. So, it is sorted in reverse order Input : 24 -&gt; 12 -&gt; 9 -&gt; 11 -&gt; 8 -&gt; 2 Output : N
8 min read
Find Length of a Linked List (Iterative and Recursive)
Write a function to count the number of nodes in a given singly linked list Examples: Input: Input: 2-&gt;4-&gt;1-&gt;9-&gt;5-&gt;3-&gt;6Output: 7 Recommended PracticeCount nodes of linked listTry It!An iterative approach for finding the length of the linked list:Follow the given steps to solve the problem: Initialize count as 0 Initialize a node p
15+ min read
Search an element in a Linked List (Iterative and Recursive)
Given a linked list and a key 'X' in, the task is to check if X is present in the linked list or not. Examples: Input: 14-&gt;21-&gt;11-&gt;30-&gt;10, X = 14Output: YesExplanation: 14 is present in the linked list. Input: 6-&gt;21-&gt;17-&gt;30-&gt;10-&gt;8, X = 13Output: No Using O(N) Extra Space. The Approach: In this approach we use vector where
15+ min read
Count half nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the half nodes (which has only one child) without using recursion? Note leaves should not be touched as they have both children as NULL. Input : Root of below treeOutput : 3 Nodes 7, 5 and 9 are half nodes as one of their child is Null. So count of half nodes in the above tree is 3 Iterative The idea is to
12 min read
Program for average of an array (Iterative and Recursive)
Given an array, the task is to find average of that array. Average is the sum of array elements divided by the number of elements. Examples : Input : arr[] = {1, 2, 3, 4, 5} Output : 3 Sum of the elements is 1+2+3+4+5 = 15 and total number of elements is 5. So average is 15/5 = 3 Input : arr[] = {5, 3, 6, 7, 5, 3} Output : 4.83333 Sum of the elemen
7 min read
Count full nodes in a Binary tree (Iterative and Recursive)
Given A binary Tree, how do you count all the full nodes (Nodes which have both children as not NULL) without using recursion and with recursion? Note leaves should not be touched as they have both children as NULL. Nodes 2 and 6 are full nodes has both child's. So count of full nodes in the above tree is 2 Method: Iterative The idea is to use leve
12 min read
Merge Two Binary Trees by doing Node Sum (Recursive and Iterative)
Given two binary trees. We need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the non-null node will be used as the node of new tree. Example: Input: Tree 1 Tree 2 2 3 / \ / \ 1 4 6 1 / \ \ 5 2 7 Output: Merged tree: 5 / \ 7 5 / \ \ 5 2 7 No
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg