您好,欢迎访问一九零五行业门户网

java如何使用递归反转字符

使用递归
package net.javaguides.corejava.string;/*** * @author yisu**/public class usingrecursion {static int i = 0;// recursive function to reverse a string in java using static variableprivate static void reverse(char[] str, int k) {// if we have reached the end of the stringif (k == str.length)return;// recurse for next characterreverse(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 emptyif (str == null || str.equals(""))return str;// convert string into a character arraychar[] a = str.tochararray();// reverse character arrayreverse(a, 0);// convert character array into the stringreturn string.copyvalueof(a);}public static void main(string[] args) {string str = "java guides";// string is immutablestr = reverse(str);system.out.println("reverse of the given string is : " + str);}}
输出:
reverse of the given string is : sediug avaj
以上就是java如何使用递归反转字符的详细内容。
其它类似信息

推荐信息