asked on
I need to write a recursive Java method that returns a string formed by moving a substring of the first n characters to the end of the string. I'm just learning recursive methods however I can't figure out how to move only part of a string to the end.
For example:
moveCharsToBack (“hello”, 2) returns “llohe”.
moveCharsToBack (“hello”, 4) would return “ohell”.
moveCharsToBack (“hello”, 5) would return “hello”.
moveCharsToBack (“hello”, 6) would return “elloh”.
This is the direction I was heading down but it doesn't even seem to be working for returning the first part correctly. It doesn't work when you pass in int of 5 or 6.
public static void main(String[] args) {
System.out.println("moveCharsToBack == " + moveCharsToBack("Hello", 2));
System.out.println("moveCharsToBack == " + moveCharsToBack("Hello", 4));
System.out.println("moveCharsToBack == " + moveCharsToBack("Hello", 5));
System.out.println("moveCharsToBack == " + moveCharsToBack("Hello", 6));
}
public static String moveCharsToBack(String input, int n) {
if (input.isEmpty()) {
return input;
}
String arr = input.substring(0, n);
String firstPart = input.substring(n, input.length());
String remainingPart;
if (arr.length() == n) {
remainingPart = arr;
}
else
remainingPart = "";
return moveCharsToBack(arr.substring(1), n - 1) + firstPart;
}
}
Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.
TRUSTED BY
ASKER
public static String moveCharsToBack(String input, int n) {
if (input.isEmpty() || n == 0 ) {
return "";
}
else
{
firstCharacter = input.charAt(0);
modifiedInput = input.substring(1) + firstCharacter;
return moveCharsToBack(modifiedInput, n - 1) + firstCharacter;
}