We're practicing recursion in class, and one of these exercises is giving me trouble (not allowed to use loops with it). I'm supposed to write a method that takes a String and an array of characters that returns the String with all of the characters in the array removed from it.
This is what I have so far. I'm struggling to get it to remove multiple characters: for example, when I input
char[] remLetArray = {'a', 's'};
System.out.println(removeLetters("asdfghsassaaaae", remLetArray));
it returns "sdfghssse". Here's the full thing:
// helper method
public static String removeLetters(String str, char[] ch, int pointer) {
if (pointer != ch[ch.length - 1]) {
if (str.length() == 0) {
return removeLetters(str, ch, pointer + 1);
}
if (str.charAt(0) == ch[pointer]) {
return removeLetters(str.substring(1), ch);
} else {
return str.charAt(0) + removeLetters(str.substring(1), ch);
}
} else {
System.out.println(str);
if (str.length() == 0) {
return "";
}
if (str.charAt(0) == ch[pointer]) {
return removeLetters(str.substring(1), ch);
} else {
return str.charAt(0) + removeLetters(str.substring(1), ch);
}
}
}
// actual method
public static String removeLetters(String str, char[] ch) {
return removeLetters(str, ch, 0);
}
You're putting way too much into carrying out the task. Make use of the String#replace() method within your removeLetter()
recursive method.
Start the pointer
value at 0
on your first call to the removeLetter()
recursive method. Within the removeLetter()
method remove the character at (pointer) index 0 then, with an if
statement, check to see if we're at the end of the char
array. If not then within the if
block increment the pointer by 1 and do another call to removeLetter()
method passing the modified string (thus far) and the new pointer (index) value. The removeLetter()
method should always return the modified input string. Here is an example:
public static String removeLetters(final String inputString, final char[] removeArray, final int pointer) {
int idx = pointer;
String newString = inputString.replace(Character.toString(removeArray[idx]), "");
if (idx < removeArray.length - 1) {
idx++;
newString = removeLetters(newString, removeArray, idx);
}
return newString;
}
char[] remLetArray = {'a', 's'};
System.out.println(removeLetters("asdfaghsassaaaae", remLetArray, 0));
dfghe