如何使用递归在 Java 中反转字符串
在这个示例程序中,我们将反转用户输入的字符串。
我们将创建一个函数来反转字符串。后面我们会递归调用,直到所有字符都反转为止。
编写一个反转字符串的 Java 程序
package com.guru99; public class ReverseString { public static void main(String[] args) { String myStr = "Guru99"; //create Method and pass and input parameter string String reversed = reverseString(myStr); System.out.println("The reversed string is: " + reversed); } //Method take string parameter and check string is empty or not public static String reverseString(String myStr) { if (myStr.isEmpty()){ System.out.println("String in now Empty"); return myStr; } //Calling Function Recursively System.out.println("String to be passed in Recursive Function: "+myStr.substring(1)); return reverseString(myStr.substring(1)) + myStr.charAt(0); } }
代码输出:
String to be passed in Recursive Function: uru99 String to be passed in Recursive Function: ru99 String to be passed in Recursive Function: u99 String to be passed in Recursive Function: 99 String to be passed in Recursive Function: 9 String to be passed in Recursive Function: String in now Empty The reversed string is: 99uruG
java