0

The recursive function receives a string and returns a new string so that each couple of chars are the first and the last char of the original. For example:

receives: abcde
returns: aebdc

receives: 1a2b3c
returns: 1ca32b
public class Ex_6 {

    public static void main(String[] args) {
        String str= "1a2b3c";// 1c a3 2b
        System.out.println(insideOut(str));
    }
    
    public static String insideOut(String str) {
        char ch= str.charAt(0);
        String newStr = "";
        if (str.length()==1 || str.length()==0 ) //the base case (a returns a)
            newStr= str;
        else            //I tried to build the new string
            newStr= ch+str.charAt(str.length()-1) + insideOut(str.substring(1, str.length()-1));
        
        return newStr;  //the output was error ("String index out of range: 0")
            
    }

1 Answer 1

1

Here is a solution for your method ->

public static String insideOut(String str) {
    char ch;
    String newStr = "";
    if (str.length() == 1 || str.length() == 0) {
        newStr = str;
    } else {
        ch = str.charAt(0);
        newStr = Character.toString(ch) + str.charAt(str.length() - 1) + insideOut(
                str.substring(1, str.length() - 1));
    }

    return newStr;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you , it works perfectly, do you think there is a a way to do it without the Character.toString() method?
Yes. You can remove char variable from the method totally and change the line in else condition like this -> newStr = "" + str.charAt(0) + str.charAt(str.length() - 1) + insideOut(str.substring(1, str.length() - 1));

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.