简体   繁体   中英

Recursive Method to return String with character at the start of the String

The question is pretty self explanatory...Design a method called startChar(String str, char c). This is a code i found here but it insert char at the end of the String. I am at a loss to think recursively. I understand this code but dont understand it enough to manipulate it to place chars at the start. Help of any kind is appreciated.

Example Input:

startChar("Apple",'p')

Output:

ppale

The code

public static String chrToLast(String str, char ch) {
    //This if statement details the end condition
    if(str.length() < 1) {
        return "";
    }


     String newString = str.substring(1); //Create new string without first 
character

    if(str.indexOf(ch) == 0) { //This happens when your character is found
        return chrToLast(newString, ch) + ch;
    } else { //This happens with all other characters
        return str.charAt(0) + chrToLast(newString, ch);
    }
}

What about...

public static void main(String[] args) {
    String s = startChar("Apple", 'p');
    System.out.println("");
}

public static String startChar(String str, char ch) {
    return startChar(str,ch,"","");
}

private static String startChar(String str, char ch, String acc, String chs) {
    //This if statement details the end condition
    if (str.length() < 1) {
        return chs + acc;
    }


    String newString = str.substring(1); //Create new string without first character

    if(str.charAt(0) == ch) { //This happens when your character is found
        return startChar(newString, ch,acc, chs + ch);
    } else { //This happens with all other characters
        return startChar(newString, ch,acc+str.charAt(0), chs);
    }
}

This is recursive with a auxiliary function

UPDATE: you must know/remember that you can procesate your data before and after the recursive call, but try to write your recursive call at the end, generally most languages has optimization in that case.

In this example we use an accumulator to accumulate processed data, then in the base step we processed those accumulator to the final output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM