如何使用递归循环从char []数组返回一个字符串。(java) [英] How to return a string from char[] array using recursion loop.(java)

查看:209
本文介绍了如何使用递归循环从char []数组返回一个字符串。(java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对递归非常不好...

I am very bad at recursion...

我需要转换一个 char [] 仅使用递归,而不使用 for() while()等循环。例如,如果我有一个char数组:

I need to convert a char[] array, using recursion only, into a string - without using for(), while() etc. loops. For example, if I have a char array:

a[0]='H', a[1]='e', a[2]='l',a[3]= 'l',a[4]= 'o'

它返回 H ello

我做错了什么?

What am I doing wrong?

 public String toFormattedString(char[] a)
 {
      int temp =a.length;
      if (a == null)
       return "null";
      if (a.length == 0)
       return "0";
       if( a.length == 1 )
           else  if( a[0] == a[a.length] )
         return toFormattedString (a[a.length -1])+a[a.length];


推荐答案

在递归中,原来的电话。这是完成,直到达到一些基本情况,其中不再可能修改数据。

In recursion, a method call itself with modified data of the original call. This is done until some base case is reached, in which is no longer possible to modify the data.

在你的情况下,基本情况是当char数组只包括一个元素。这个字符串将是字符串。否则,它是第一个元素,其余的在递归调用中追加。

In your case the base case is when the char array only consist of one element. This char will be the String. Otherwise it is the first element with the rest appended in a recursive call.

字符串Hello'H' toFormattedString({'e','l','l','o'})附加。所以如果你的char数组只包含一个元素(length == 1)只是返回这个元素作为String值。

The String "Hello" is 'H' with toFormattedString({'e','l','l','o'}) appended. So if your char array contains only of one element (length==1) just return this element as String value.

否则取第一个元素,并递归到没有第一个元素的剩余的char数组。递归直到它只剩下一个元素。

Otherwise take the first-element and go recursive to the remaining char array without the first element. Recursive until it is only one element left.

    public static String toFormattedString(char[] a)
{
     if (a.length==1) return String.valueOf(a[0]);
     else     
     return a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length)) ;

}

您甚至可以将方法体放在一个不可读的行不推荐,我提到它只是为了乐趣):

You can even put the method body in one unreadable line(not recommended, I mentioned it just for fun):

return((a.length==1)?String.valueOf(a[0]):a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length)));

UPDATE: A 切换 -statement在这个例子中给出可读代码:

UPDATE: A switch-statement gives readable code in this example:

public static String toFormattedString(char[] a)
 {
    switch (a.length)
      {case 0 : return "";    
       case 1 : return String.valueOf(a[0]);
       default: return a[0]+toFormattedString(Arrays.copyOfRange(a,1,a.length));
      }
}

用法:

 public static void main (String[] args) throws java.lang.Exception
{  
    System.out.println(toFormattedString("Hello".toCharArray()));
}

这篇关于如何使用递归循环从char []数组返回一个字符串。(java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆