java如何使用递归反转字符
作者:WeekendFlower
时间:2023-05-03
浏览:0
使用递归packagenet.javaguides.corejava.string;/****@authoryisu**/publicclassUsingRecursion{staticinti=0;//RecursivefunctiontoreverseastringinJavausingstaticvariableprivatestaticvoidreverse(char[]str,intk){//ifwehavereachedtheendofthestringif(k==str.length)ret
本文目录
使用递归
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
作者最新文章
ArchiveofOurOwn官网链接及同人文学阅读入口
2026-10-30 10:21
多张照片怎么合成PDF文件?三种图片转PDF工具怎么选?
2026-10-29 15:06
音述AI作品如何复制分享链接发给好友
2026-10-27 12:00
冰点还原怎么打开 程序启动步骤
2026-10-23 13:35
keyshot怎么做爆炸图 零件展开步骤
2026-10-21 10:46
上一篇:
如何从 iPhone 中恢复数据?
下一篇:
Python怎么获取视频文件的大小和时长
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多

































