使用递归
package net.javaguides.corejava.string; /** * * @author yisu * */ public class UsingRecursion { static int i = 0; // Recursive function to reverse a string in Java using static variable private static void reverse(char[] str, int k) { // if we have reached the end of the string if (k == str.length) return; // recurse for next character reverse(str, k + 1); if (i <= k) { char temp = str[k]; str[k] = str[i]; str[i++] = temp; } } public static String reverse(String str) { // base case: if string is null or empty if (str == null || str.equals("")) return str; // convert string into a character array char[] A = str.toCharArray(); // reverse character array reverse(A, 0); // convert character array into the string return String.copyValueOf(A); } public static void main(String[] args) { String str = "Java Guides"; // string is immutable str = reverse(str); System.out.println("Reverse of the given string is : " + str); } }
输出:
Reverse of the given string is : sediuG avaJ
以上就是java如何使用递归反转字符的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号