我有一个递归方法来反转字符串(硬件分配,必须是递归的)。我做到了......但它只在第一次传递后返回字符串的值。通过分析每次传递后的输出,我可以看到它确实正确地完成了它的工作。这是我的代码,以及我在其下面得到的输出:
String s = "Hello, I love you wont you tell me your name?";
int k=0;
public String reverseThisString(String s) {
if(k!=s.length()) {
String first =s.substring(0,k)+s.charAt(s.length()-1);
String end = ""+s.substring(k, s.length()-1);
k++;
s=first+end;
System.out.println(s);
this.reverseThisString(s);
}
return s;
}
输出:
?Hello, I love you wont you tell me your name
最佳答案
我认为你需要改变这一点:
this.reverseThisString(s);
对此:
return this.reverseThisString(s);
否则方法调用的结果将被简单地丢弃。
我还建议您将 k 更改为方法的参数而不是成员。
关于java - 为什么这不返回新字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4910290/