开发者

How to return a string from char[] array using recursion loop.(java)

开发者 https://www.devze.com 2023-02-03 08:57 出处:网络
I am very bad at recursion... I need to convert achar[] array, using recursion only, into a string - without using for(), while() etc. loops. For example, if I have a char array:

I am very bad at recursion...

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'

it retur开发者_运维百科ns H e l l o.

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.

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.

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.

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 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));
      }
}

Usage:

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


Why doint this way if you have new String(char[])

Using recursion ,

I would strongly suggest you to understand recursion and this code well before you submit your HW.

package org.life.java.so.questions;

/**
 *
 * @author Jigar
 */
public class StringCharRec {

    public static String toStringFromCharArr(String str, char[] arr, int pos) {
        if (pos == arr.length) {

            return str;
        }
        str += Character.toString(arr[pos]);
        return toStringFromCharArr(str, arr, ++pos);


    }

    public static void main(String[] args) {
        char[] ar = {'a', 'b', 'c'};
        System.out.println(toStringFromCharArr(new String(), ar, 0));
    }
}


public String toFormattedString(char ch[]){ if(ch.length <= 0) return "";return ch[0] + (toFormattedString(new String(ch).substring(1).toCharArray()));}


Yet another answer.

public String toFormattedString(char[] a) {
   return a == null ? "null" : toFormattedString(a, 0);
}

private String toFormattedString(char[] a, int pos) {
   return pos >= a.length ? "" : a[pos] + toFormattedString(a, pos+1);
}

This divides the string in half each time. This won't blow up on long strings. (Doing one character at a time could case a StackOverFlowError ;)

public String toFormattedString(char[] a) {
   return a == null ? "null" : toFormattedString(a, 0, a.length);
}

private String toFormattedString(char[] a, int start, int end) {
   int len = end-start;
   return len==0?"":len==1?""+a[start]:
     toFormattedString(a,start,start+len/2)+toFormattedString(a,start+len/2,end);
}

I don't see how this is a "formatted" string. There is no formatting, its just a string.

0

精彩评论

暂无评论...
验证码 换一张
取 消