How to remove all the characters in char array from a given string recursively without using loops?

时间:2015-06-15 14:42:41

标签: java recursion

I am practicing Java tutorial and I am trying to remove all the characters given in char array from a given string (e.g. array contains 'b', 'm', 'w'. Target string is "big workshop", output: "ig orkshop"). But I cannot use loops and I should do it recursively. I have managed it without recursion but not with recursion. This is my non-recursive code:

char[] testChars={'E', 'i', 'n'}; 
String b = new String(testChars); 
... 
public static String removeChars(String text) 
{ 
 return text.replaceAll("[" + b + "]", ""); 
} 

5 个答案:

答案 0 :(得分:1)

Try this,

public class Example
{
   public static void main(String[] agrs) {
       String input = "big workshop";
       char[] charToRemove = {'b', 'm', 'w'};
       String charsToRemove = new String(charToRemove);
       StringBuilder sb = new StringBuilder();
       Example ex = new Example();
       ex.removeChar(input, 0, charsToRemove, sb);
       System.out.println(sb);

   }

   public void removeChar(String input, int index, String charToRemove, StringBuilder target) {

       if(input.length() == index) {
           return;
       }

       char c = input.charAt(index);
       if(charToRemove.indexOf(c) == -1) {
           target.append(c);
       }

       removeChar(input, index + 1, charToRemove, target);

   }

}

答案 1 :(得分:1)

Try:

public static String removeChars(String text, char[] chars) {
    return removeChars(text, chars, 0);
}

private static String removeChars(String text, char[] chars, int currentIndex) {
    if(currentIndex == chars.length) {
        return text;
    }
    char currentChar = chars[currentIndex];
    String removed = text.replace(currentChar.toString(), "");
    return removeChars(removed, chars, currentIndex + 1);
}

答案 2 :(得分:1)

When trying to use recursion, you have two remember that you are either at a base case or taking a step toward it.

For example: your base case could be the end of the string. You have two possibilities at each recursive level.

1) you are at the end of the string: return an empty string to use as a building base.

2) you are not at the end of the string: you can check the first character and pass the rest of the string to a recursive call.

See the example below. This is not tested code but should point you in the right direction.

public String recursiveRemove (String[] arr, String str){
    // first check if at the base case
    if (str.length() == 0) {
        return "";
    }
    // else handle character, and reduce to approach base case
    String character = str.substring(0,1);
    // contains is not a method but just to show the logic being used here
    if (arr.contains(character)){ 
        //replace character with empty sting to remove it from the result
        character = "";
    }
    // return the character (or empty string) with the result of the 
    // recursive call appended onto the end
    return character + recursiveRemove(arr, str.substring(1));
}

答案 3 :(得分:0)

You can replace for-loops this way:

public void replaceFor(int i , Predicate<Integer> p , Consumer<Integer> c , Function<Integer , Integer> f)
{
    //check whether the termination-condition is true
    if(!p.test(i))
        return;

    //this consumer does what would be in the for-loop
    c.accept(i);

    //continue with the next value for i
    replaceFor(f.apply(i) , p , c , f);
}

A basic for-loop replacement that prints all numbers from 0 to 10 would look like this:

replaceFor(0 , i -> i <= 10 , i -> System.out.println(i) , i -> ++i);

答案 4 :(得分:0)

这是

的解决方案
  • 维护您的方法签名
  • 不使用递归屏蔽迭代
  • 教你划分和征服

注意,我对testChars字段并不感到兴奋,但看起来你的迭代版本已经有了这个。

private final static char[] testChars = {'b', 'm', 'w'};

  public static String removeChars(String text) {
    switch (text.length()) {
      case 0:
        return "";
      case 1:
        char asChar = text.charAt(0);
        for (char testChar : testChars) {
          if (asChar == testChar) {
            return "";
          }
        }
        return text;
      default:
        int middle = text.length() / 2;
        String firstHalf = text.substring(0, middle);
        String lastHalf = text.substring(middle);
        return removeChars(firstHalf) + removeChars(lastHalf);
    }

  }

  public static void main(String... args) {
    System.out.println(removeChars("big workshop"));
  }