# 使用递归来反转字符串的 Java 程序

> 原文： [https://beginnersbook.com/2017/09/java-program-to-reverse-a-string-using-recursion/](https://beginnersbook.com/2017/09/java-program-to-reverse-a-string-using-recursion/)

我们将看到两个程序来反转一个字符串。第一个程序使用递归反转给定的字符串，第二个程序读取用户输入的字符串然后反转它。

要了解这些程序，你应该具备以下[核心 java](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/) 概念的知识：
1）[

中的](https://beginnersbook.com/2013/12/java-string-substring-method-example/) [substring（）2）](https://beginnersbook.com/2013/12/java-string-substring-method-example/) [charAt（）方法](https://beginnersbook.com/2013/12/java-string-charat-method-example/)

## 示例 1：用于反转字符串的程序

```java
public class JavaExample {

    public static void main(String[] args) {
        String str = "Welcome to Beginnersbook";
        String reversed = reverseString(str);
        System.out.println("The reversed string is: " + reversed);
    }

    public static String reverseString(String str)
    {
        if (str.isEmpty())
            return str;
        //Calling Function Recursively
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}
```

**输出：**

```java
The reversed string is: koobsrennigeB ot emocleW
```

## 示例 2：用于反转用户输入的字符串的程序

```java
import java.util.Scanner;
public class JavaExample {

    public static void main(String[] args) {
        String str;
        System.out.println("Enter your username: ");
        Scanner scanner = new Scanner(System.in);
        str = scanner.nextLine();
        scanner.close();
        String reversed = reverseString(str);
        System.out.println("The reversed string is: " + reversed);
    }

    public static String reverseString(String str)
    {
        if (str.isEmpty())
            return str;
        //Calling Function Recursively
        return reverseString(str.substring(1)) + str.charAt(0);
    }
}
```

**Output:**

```java
Enter your username: 
How are you doing?
The reversed string is: ?gniod uoy era woH
```