76.md 2.2 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6 7
# 使用递归来反转字符串的 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/) 概念的知识:
W
wizardforcel 已提交
8

W
wizardforcel 已提交
9 10 11 12 13 14
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:用于反转字符串的程序

W
wizardforcel 已提交
15
```java
W
wizardforcel 已提交
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
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);
    }
}
```

**输出:**

W
wizardforcel 已提交
36
```java
W
wizardforcel 已提交
37 38 39 40 41
The reversed string is: koobsrennigeB ot emocleW
```

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

W
wizardforcel 已提交
42
```java
W
wizardforcel 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
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);
    }
}
```

W
wizardforcel 已提交
66
**输出:**
W
wizardforcel 已提交
67

W
wizardforcel 已提交
68
```java
W
wizardforcel 已提交
69 70 71 72
Enter your username: 
How are you doing?
The reversed string is: ?gniod uoy era woH
```