gpt4 book ai didi

Java - 使用递归反转字符串

转载 作者:行者123 更新时间:2023-12-02 12:05:42 25 4
gpt4 key购买 nike

private static String stringReverseRecursive(String str)
{
// saves the last letter of the word in the variable c
char c = str.charAt (str.length()-1);
// take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
return c + stringReverseRecursive((str.substring(0,str.length()-1)));

}

当我尝试调用该函数时,编译器会给出一个错误,指出它超出了范围。我认为 lat 线和 char c 线有问题。

最佳答案

private static String stringReverseRecursive(String str)
{
if (str.isEmpty()) {

return str;
}

// saves the last letter of the word in the variable c
char c = str.charAt (str.length()-1);
// take the last letter saved in c and joins the sub string of everything without the first letter and runs it again.
return c + stringReverseRecursive((str.substring(0,str.length()-1)));

}

您想要检查长度是否为 0,以满足空字符串的需要,例如“”

if 语句允许您的代码完成执行,可以称为基本情况。

关于Java - 使用递归反转字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46922635/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com