如何将我的while循环重写为递归?

512*_*bee 1 java iteration recursion while-loop

如何编写我的以下代码,以便它不迭代但使用递归代替(即删除while循环):

public static void addSlashes(String str)
{
    int i = 0;

    if (str.length() != 0){
         while (i < str.length()){
              // get character at current 'i' index of string,
              // then adds a "/" after it:
              System.out.print(str.charAt(i) + "/");
              i++;
         }
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,while循环是递归还是迭代?我认为它是迭代的,因为它一次又一次地重复参数中字符串的长度.

使用此方法的示例输出可能是:

addSlashes("Hello");

H/e/l/l/o
Run Code Online (Sandbox Code Playgroud)

Hen*_*sen 5

使用substring和仅使用String参数:

public static void addSlashes(String str) {
    if (str.isEmpty())
        return;

    System.out.print(str.charAt(0) + "/");
    addSlashes(str.substring(1));
}
Run Code Online (Sandbox Code Playgroud)

请注意,这是一种相当低效的方法,因为它实际上会length String在大多数Java运行时中创建实例.

在这里运行它.