Program to reverse a string (Iterative and Recursive)

Given a string, write a recursive program to reverse it.

string-reverse



Method 1 (Using Stack)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to reverse a string using stack
#include <bits/stdc++.h>
using namespace std;
  
void recursiveReverse(string &str)
{
   stack<char> st;
   for (int i=0; i<str.length(); i++)
       st.push(str[i]);
  
   for (int i=0; i<str.length(); i++) {
       str[i] = st.top();
       st.pop();
   }       
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    recursiveReverse(str);
    cout << str;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to reverse a string using stack
import java.util.*;
class GFG
{
  public static String recursiveReverse(char []str) 
 
   Stack<Character> st = new Stack<>(); 
   for(int i=0; i<str.length; i++) 
        st.push(str[i]); 
  
   for (int i=0; i<str.length; i++) { 
    str[i] = st.peek(); 
    st.pop(); 
   }     
   return String.valueOf(str);// converting character array to string
 
  
// Driver program 
   public static void main(String []args) 
   
      String str = "geeksforgeeks"
      str = recursiveReverse(str.toCharArray());// passing character array as parameter 
      System.out.println(str); 
   }
}
//Contributed by Adarsh_Verma

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to reverse a string using stack 
using System;
using System.Collections.Generic;
  
class GFG 
    public static String recursiveReverse(char []str) 
    
        Stack<char> st = new Stack<char>(); 
        for(int i = 0; i < str.Length; i++) 
            st.Push(str[i]); 
  
        for (int i = 0; i < str.Length; i++) 
        
            str[i] = st.Peek(); 
            st.Pop(); 
        
          
        // converting character array to string
        return String.Join("",str); 
    
  
    // Driver program 
    public static void Main() 
    
        String str = "geeksforgeeks"
          
        // passing character array as parameter
        str = recursiveReverse(str.ToCharArray()); 
        Console.WriteLine(str); 
    
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

skeegrofskeeg

Time complexity : O(n)
Auxiliary Space : O(n)

Method 2 (Iterative)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple Iterative C++ program to reverse
// a string
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str)
{
    int n = str.length();
  
    // Swap character starting from two
    // corners
    for (int i = 0; i < n / 2; i++)
        swap(str[i], str[n - i - 1]);
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple Java program 
// to reverse a string
import java.util.Scanner;
  
public class reverseStr
{
// Function to reverse 
// a string
void stringReverse()
{
    String str = "geeksforgeeks";
    int length = str.length();
    StringBuffer revString = new StringBuffer();
    for (int i = length - 1
             i >= 0; i--) 
    {
        revString.append(str.charAt(i));
    }
    System.out.println(revString);
}
  
// Driver Code
public static void main(String []args)
{
    reverseStr s= new reverseStr();
    s.stringReverse();
}
}
  
// This code is contributed 
// by prabhat kumar singh 

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# A Simple python program 
# to reverse a string
  
# Function to
# reverse a string
def reverseStr(str):
    n = len(str)
      
    # initialising a empty
    # string 'str1'
    str1 = ''
    i = n - 1
    while i >= 0:
          
        # copy str 
        # to str1
        str1 += str[i]
        i -= 1
    print(str1)     
  
# Driver Code 
def main():
    str = "geeksforgeeks";
    reverseStr(str);
      
if __name__=="__main__":
    main()     
      
# This code is contributed 
# by prabhat kumar singh 

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A Simple Iterative PHP 
// program to reverse
// a string
  
// Function to reverse a string
function reverseStr(&$str)
{
    $n = strlen($str);
  
    // Swap character starting 
    // from two corners
    for ($i = 0; $i < $n / 2; $i++)
        //swap the string
        list($str[$i], 
             $str[$n - $i - 1]) = array($str[$n - $i - 1], 
                                        $str[$i]);
}
  
// Driver Code
$str = "geeksforgeeks";
  
reverseStr($str);
echo $str;
  
// This code is contributed by ajit
?>

chevron_right


Output:

skeegrofskeeg

Time complexity : O(n)
Auxiliary Space : O(1)

Method 3 (Iterative using two pointers)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple Iterative C++ program to reverse
// a string
#include <bits/stdc++.h>
using namespace std;
  
// Function to reverse a string
void reverseStr(string& str)
{
    int n = str.length();
  
    // Swap character starting from two
    // corners
    for (int i=0, j=n-1; i<j; i++,j--)
        swap(str[i], str[j]);  
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    reverseStr(str);
    cout << str;
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

//A Simple Iterative Java program to reverse
//a string
class GFG {
  
    //Function to reverse a string
    static void reverseStr(String str)
    {
     int n = str.length();
     char []ch = str.toCharArray();
     char temp;
  
     // Swap character starting from two
     // corners
     for (int i=0, j=n-1; i<j; i++,j--)
     {
         temp = ch[i];
         ch[i] = ch[j];
         ch[j] = temp;
     }
          
       
     System.out.println(ch);
    }
  
    //Driver program
    public static void main(String[] args) {
          
        String str = "geeksforgeeks";
         reverseStr(str);
    }
}
// This code is contributed by Ita_c. 

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple Iterative C# program  
// to reverse a string 
using System;
  
class GFG 
  
    //Function to reverse a string 
    static void reverseStr(String str) 
    
        int n = str.Length; 
        char []ch = str.ToCharArray(); 
        char temp; 
  
        // Swap character starting from two 
        // corners 
        for (int i=0, j=n-1; i<j; i++,j--) 
        
            temp = ch[i]; 
            ch[i] = ch[j]; 
            ch[j] = temp; 
        
        Console.WriteLine(ch); 
    
  
    //Driver program 
    public static void Main(String[] args)
    
        String str = "geeksforgeeks"
        reverseStr(str); 
    
  
// This code is contributed by PrinciRaj1992

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php
// A Simple Iterative PHP 
// program to reverse a string
  
// Function to reverse a string
function reverseStr (&$str)
{
    $n = strlen($str);
  
    // Swap character starting
    // from two corners
    for ($i = 0, $j = $n - 1; 
         $i < $j; $i++, $j--)
        //swap function 
        list($str[$i], 
             $str[$j]) = array($str[$j], 
                               $str[$i]);
}
  
// Driver Code
$str = "geeksforgeeks";
reverseStr($str);
echo $str;
  
// This code is contributed by ajit.
?>

chevron_right


Output:

skeegrofskeeg

Time complexity : O(n)
Auxiliary Space : O(1)

Method 4 (Recursive)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// Recursive C++ program to reverse a string
#include <bits/stdc++.h>
using namespace std;
  
void recursiveReverse(string &str, int i = 0)
{
    int n = str.length();
    if (i == n / 2)
        return;
    swap(str[i], str[n - i - 1]);
    recursiveReverse(str, i + 1);
}
  
// Driver program
int main()
{
    string str = "geeksforgeeks";
    recursiveReverse(str);
    cout << str;
    return 0;
}

chevron_right


Output:

skeegrofskeeg

Time complexity : O(n)
Auxiliary Space : O(n)

Method 5 (Library function)

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// A quickly written program for reversing a string
// using reverse()
#include<bits/stdc++.h>
using namespace std;
int main()
{
   string str = "geeksforgeeks";
      
   // Reverse str[beign..end]
   reverse(str.begin(),str.end());
      
   cout << str;
   return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// A Simple Java program 
// to reverse a string
  
class GFG
{
  
    public static void main(String[] args) 
    {
        String str = "geeksforgeeks";
          
        // Reverse str[beign..end] 
        str = reverse(str);
  
        System.out.println(str);
    }
  
    static String reverse(String input) 
    {
        char[] temparray = input.toCharArray();
        int left, right = 0;
        right = temparray.length - 1;
  
        for (left = 0; left < right; left++, right--) 
        {
            // Swap values of left and right 
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right] = temp;
        }
        return String.valueOf(temparray);
    }
  
// This code is contributed by 29AjayKumar

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# A Simple python program 
# to reverse a string
  
# Function to 
# reverse a string
def reverseStr(str):
      
    # print the string
    # from last
    print(str[::-1])     
  
# Driver Code 
def main():
    str = "geeksforgeeks";
    reverseStr(str);
      
if __name__=="__main__":
    main()     
      
# This code is contributed 
# by prabhat kumar singh 

chevron_right


PHP

Output:

skeegrofskeeg


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.