我们将看到两个程序来反转一个字符串。第一个程序使用递归反转给定的字符串,第二个程序读取用户输入的字符串然后反转它。
示例 1:用于反转字符串的程序
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);
}
}
输出:
The reversed string is: koobsrennigeB ot emocleW
示例 2:用于反转用户输入的字符串的程序
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);
}
}
输出:
Enter your username:
How are you doing?
The reversed string is: ?gniod uoy era woH