📜  使用递归打印字符串的反转

📅  最后修改于: 2022-05-13 01:57:08.111000             🧑  作者: Mango

使用递归打印字符串的反转

编写一个递归函数来打印给定字符串的反转。
程序:

C++
// C++ program to reverse a string using recursion
#include 
using namespace std;
 
/* Function to print reverse of the passed string */
void reverse(string str)
{
    if(str.size() == 0)
    {
        return;
    }
    reverse(str.substr(1));
    cout << str[0];
}
 
/* Driver program to test above function */
int main()
{
    string a = "Geeks for Geeks";
    reverse(a);
    return 0;
}
 
// This is code is contributed by rathbhupendra


C
// C program to reverse a string using recursion
# include 
 
/* Function to print reverse of the passed string */
void reverse(char *str)
{
   if (*str)
   {
       reverse(str+1);
       printf("%c", *str);
   }
}
 
/* Driver program to test above function */
int main()
{
   char a[] = "Geeks for Geeks";
   reverse(a);
   return 0;
}


Java
// 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);
    }   
}


Python
# Python program to reverse a string using recursion
 
# Function to print reverse of the passed string
def reverse(string):
    if len(string) == 0:
        return
     
    temp = string[0]
    reverse(string[1:])
    print(temp, end='')
 
# Driver program to test above function
string = "Geeks for Geeks"
reverse(string)
 
# A single line statement to reverse string in python
# string[::-1]
 
# This code is contributed by Bhavya Jain


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


PHP


Javascript


输出:

skeeG rof skeeG