使用递归反转句子 Java 程序
在本文中,我们将了解如何使用递归反转句子。递归函数是指多次调用自身直到满足特定条件的函数。
递归函数是指多次调用自身直到满足特定条件的函数。
递归是重复以自相似方式出现的项目的过程。在编程语言中,如果一个程序允许你在同一个函数内部调用一个函数,那么它被称为该函数的递归调用。
许多编程语言通过栈来实现递归。通常,每当一个函数(调用方)调用另一个函数(被调用方)或自身作为被调用方时,调用方函数都会将执行控制权转移到被调用方。此转移过程可能还涉及将某些数据从调用方传递到被调用方。
以下是相同内容的演示 -
输入
假设我们的输入是 -
Enter the sentence : Have a nice evening
输出
期望的输出将是 -
The reversed input is: gnineve ecin a evaH
算法
Step 1 - START Step 2 - Declare two string values namely my_input and my_result Step 3 - Read the required values from the user/ define the values Step 4 - A recursive function ‘reverseString is defined which takes an string as input and returns the character at the last position. Step 5 - The function is called recursively until the value of ‘my_input’ is not an empty string. Step 6 - The recursive function is called and the value ‘my_input’ is passed to it. Store the return value Step 7 - Display the result Step 8 - Stop
示例 1
这里,输入是由用户根据提示输入的。您可以在我们的编码环境工具 中实时尝试此示例。
import java.util.Scanner; public class Reverse { public static void main(String[] args) { String my_input, my_result; System.out.println("Required packages have been imported"); Scanner my_scanner = new Scanner(System.in); System.out.println("A reader object has been defined "); System.out.print("Enter the sentence : "); my_input = my_scanner.nextLine(); my_result = reverseString(my_input); System.out.println("The reversed input is: " + my_result); } public static String reverseString(String my_input) { if (my_input.isEmpty()) return my_input; return reverseString(my_input.substring(1)) + my_input.charAt(0); } }
输出
Required packages have been imported A reader object has been defined Enter the sentence : Have a nice evening The reversed input is: gnineve ecin a evaH
示例 2
这里,整数已预先定义,并访问其值并在控制台上显示。
public class Reverse { public static void main(String[] args) { String my_input, my_result; my_input = "Have a nice evening"; System.out.println("The string is defined as :" +my_input); my_result = reverseString(my_input); System.out.println("The reversed input is: " + my_result); } public static String reverseString(String my_input) { if (my_input.isEmpty()) return my_input; return reverseString(my_input.substring(1)) + my_input.charAt(0); } }
输出
The string is defined as :Have a nice evening The reversed input is: gnineve ecin a evaH
广告