user3752134
0
Q:

reverse a string in java recursion

public static String reverse(String str) {
    if ((null == str) || (str.length() <= 1)) {
        return str;
    }
    return reverse(str.substring(1)) + str.charAt(0);
}
1
// Java program to reverse a string using recursion 
  
class StringReverse 
{ 
    /* Function to print reverse of the passed string */
    void reverse(String str) 
    { 
        if ((str==null)||(str.length() <= 1)) 
           System.out.println(str); 
        else
        { 
            System.out.print(str.charAt(str.length()-1)); 
            reverse(str.substring(0,str.length()-1)); 
        } 
    } 
      
    /* Driver program to test above function */
    public static void main(String[] args)  
    { 
        String str = "Geeks for Geeks"; 
        StringReverse obj = new StringReverse(); 
        obj.reverse(str); 
    }     
} 
0
public class Test {

    private static int i = 0;

    public static void main(String args[]) {
        reverse("Hello");
    }

    public static String reverse(String str) {
        int localI = i++;
        if ((null == str) || (str.length()  <= 1)) {
            return str;
        }
        System.out.println("Step " + localI + ": " + str.substring(1) + " / " + str.charAt(0));
        String reversed = reverse(str.substring(1)) + str.charAt(0);

        System.out.println("Step " + localI + " returns: " + reversed);
        return reversed;
    }
}
0
<?php 
// PHP program to reverse  
// a string using recursion 
  
// Function to print reverse 
// of the passed string 
function reverse($str) 
{ 
    if (($str == null) ||  
        (strlen($str) <= 1)) 
    echo ($str); 
  
    else
    { 
        echo ($str[strlen($str) - 1]); 
        reverse(substr($str, 0,  
               (strlen($str) - 1))); 
    } 
} 
  
// Driver Code 
$str = "Geeks for Geeks"; 
reverse($str); 
  
// This code is contributed by  
// Manish Shaw(manishshaw1) 
?> 
0
// C# program to reverse  
// a string using recursion 
using System; 
  
class GFG 
{ 
    // Function to print reverse 
    // of the passed string 
    static void reverse(String str) 
    { 
        if ((str == null) || (str.Length <= 1)) 
        Console.Write(str); 
      
        else
        { 
            Console.Write(str[str.Length-1]); 
            reverse(str.Substring(0,(str.Length-1))); 
        } 
    } 
      
    // Driver Code 
    public static void Main()  
    { 
        String str = "Geeks for Geeks"; 
        reverse(str); 
    }  
} 
  
// This code is contributed by Sam007 
0

New to Communities?

Join the community