java - 字符串的无效递归反转方法

标签 java string recursion reverse void

我在这里看到了很多关于字符串的递归反向方法的问题,答案是它们应该添加 String 作为参数。对于赋值,该方法必须为 void。这就是我所拥有的“String next = other + firstChar;”错误是因为它不能组合这两种类型,因为“other”是一个句子变量。我如何构建它才能添加它们?

public void reverse()
{
   //implement a recursive method
   if (text.isEmpty()){
         return;
   }
   else 
   {
       char firstChar = text.charAt(0);
       String otherCharacters = text.substring(1, text.length());
       Sentence other = new Sentence(otherCharacters);
       other.reverse();
       String next = other + firstChar;
       text = next;
    }
}

最佳答案

不确定 Sentence 类是如何实现的,示例递归 void 可能如下所示:

static String reversed = "";
static String input = "String to reverse";
static int pos = 0;

static void reverse() {
    if (pos == input.length()) {
        return;
    } 
    reversed += input.charAt(input.length() - 1 - pos++);
    reverse();
}

关于java - 字符串的无效递归反转方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61333278/

相关文章:

java - Vaadin 上传教程中出现 "Can not resolve symbol"错误

java - 在 paint 方法中调用时 JLabel 不显示

javascript - 在javascript中将字符串转换为函数

c# - 反射:递归地搜索字符串值的对象,然后报告路径

recursion - 在Prolog中学习递归

php - 在 PHP 中的嵌套关​​联数组中搜索值并返回其路径

java - FTP进度条上传文件

java - 如何获取 AJAX 生成的 HTML 文本?

python - 在 sql 查询 python 中使用时,格式选项不起作用

php - 如何从 php 中的字符串中删除 ♥(或 ♥)?