0

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 returns 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];
3
  • Don�?t the compiler show any errors? Commented Jan 8, 2011 at 9:49
  • He is. But it doesn't help me to understand the root of the problem. :( Commented Jan 8, 2011 at 9:56
  • 1
    You are also pretty bed at spelling :-) Commented Jan 8, 2011 at 10:09

4 Answers 4

1

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

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));
    }
}
1
  • That's what my teacher want's. The method have to start with public String toFormattedString(char[] a) { Commented Jan 8, 2011 at 9:58
0

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

1
  • 1
    I like the use of new String(char[]) to do what the function is supposed to do. ;) Commented Jan 8, 2011 at 14:09
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.