How to Remove Given Character From String in Java - Recursion

Write a program to remove a given character from String in Java. Your program must remove all occurrences of given character. For example, if given String is "aaaaa" and String to remove is "a" then output should be an empty String. Similarly if input String is "abc" and character to remove is "b" then your program must return "ac" as output. You are not allowed to use any JDK method or third party method which solves this method directly, but you can use basic String manipulation method like indexOf(), toChar() or substring() from java.lang.String class. Most important thing is, you must code the logic to solve the problem by yourself. You should also write the solution using both Iterative and Recursive algorithms. An Iterative algorithm is the one which make use of loops e.g. for loop, while loop or do while loop, which recursive solution should not use any loop. Now let's think how can we solve this problem? Most simple solution which comes in my mind is to iterate over String by converting into character array and check if current character is same as given character to remove or not, if it is then ignore it otherwise add character into StringBuilder. At the end of iteration you will have a StringBuilder with all character except the one which is asked to remove, just convert this StringBuilder to String and your solution is ready. This solution should have space complexity of O(n) because you need an extra buffer of same size as original String and time complexity will also be O(n) because you need to loop over all elements of String. Can you make it better? because this solution will not work for large String, especially if you have memory constraint. Now, let's see how to remove character from String recursively?BTW, this is one of the good coding question and has been asked in companies like Goldman Sachs, Amazon and Microsoft. So if you are preparing for programming job interviews, make sure you include this question in your list as well.




Removing a given Character From String Recursively

In order to solve this problem recursively, we need a base case and a process which reduce the problem space after each recursive step. We can solve this problem using indexOf() and substring() method of Java's String class, indexOf() method returns index of a given character if its present in the String on which this method is called, otherwise -1. So first step, we will try to find the index of given character, if its present then we will remove it using substring() method, if not present then it become our base case and problem is solved.

Here is our sample program to recursively remove all occurrences of a given character.

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
  * Java program to remove given character from a given String using loops and recursion,
  * asked as coding question to Java programmers.
  *
  * @author Javin Paul
  */
public class RemoveCharFromString {

    private static final Logger logger = LoggerFactory.getLogger(RemoveCharFromString.class);
 
    public static String remove(String word, char unwanted){
        StringBuilder sb = new StringBuilder();
        char[] letters = word.toCharArray();
     
        for(char c : letters){
            if(c != unwanted ){
                sb.append(c);
            }
        }
     
        return sb.toString();
    }
 
    public static String removeRecursive(String word, char ch){
        int index = word.indexOf(ch);
        if(index == -1){
            return word;
        }
        return removeRecursive(word.substring(0, index) + word.substring(index +1, word.length()), ch);
    }
}

You can see that we have two method, both accept one String and a character which needs to be removed from the given String. The first method, remove(String word, char unwanted) deletes the given character using iteration while second method removeRecursive(String word, char ch), uses recursion to accomplish this task.


Unit Testing of Solution

Here is our suite of JUnit tests to check whether this program is working properly or not. We have unit test to check removing a character from beginning, middle and end. We also have unit test for corner cases like removing the only character String contains, or removing character from String which contains same character multiple times. You can also add other tests for checking with empty String, NULL and trying to remove a character which is not present in the String. One thing to note here is that, we are testing both of our remove() method, one which removes given character using iteration and other which removes specified character using recursion.

import static org.junit.Assert.*;

import org.junit.Test;

/**
  * JUnit test to for unit testing our remove() utility method, which accepts
  * an String and a character, to remove all occurrences of that character
  * from that String.

  * @author Javin
  */    
public class RemoveCharFromStringTest {

    @Test
    public void removeAtBeginning(){
        assertEquals("bc", RemoveCharFromString.remove("abc", 'a'));
        assertEquals("bc", RemoveCharFromString.removeRecursive("abc", 'a'));
     
        assertEquals("bcdefgh", RemoveCharFromString.removeRecursive("abcdefgh", 'a'));
        assertEquals("bcdefgh", RemoveCharFromString.removeRecursive("abcdefgh", 'a'));
    }
 
    @Test
    public void removeAtMiddle(){
        assertEquals("abd", RemoveCharFromString.remove("abcd", 'c'));
        assertEquals("abd", RemoveCharFromString.removeRecursive("abcd", 'c'));
    }
 
 
    @Test
    public void removeAtEnd(){
        assertEquals("abc", RemoveCharFromString.remove("abcd", 'd'));
        assertEquals("abc", RemoveCharFromString.removeRecursive("abcd", 'd'));
    }
 
    @Test
    public void cornerCases(){
        // empty string test
        assertEquals("", RemoveCharFromString.remove("", 'd'));
     
        // all removable character test
        assertEquals("", RemoveCharFromString.remove("aaaaaaaaaaaaaa", 'a'));
     
        // all but one removable characters
        assertEquals("b", RemoveCharFromString.remove("aaaaaaaaaaaaaab", 'a'));
    }

}

and here is the Output of running our JUnit tests in Eclipse IDE :

Testsuite: RemoveCharFromStringTest
Tests run: 4, Failures: 0, Errors: 0, Time elapsed: 0.172 sec
Java Program to remove given Character from String


That's all about how to remove a given character from given String in Java. This is a question which often appears in various Java interviews, written test and telephonic round. You should remember both iterative and recursive algorithm to solve this problem and pros and cons of each approach.

If you like solving coding problems like this and wants to do more, checkout this amazing set of coding problems from programming interviews and courses :
  • How to solve FizzBuzz in Java 8? (solution)
  • How to check if a linked list contains cycle? (solution)
  • How to find kth element from last in one pass in singly linked list? (solution)
  • How to find largest prime factor of a number in Java? (solution)
  • How do you reverse array in place in Java? (solution)
  • How to check if given number is binary in Java? (solution)
  • How to Swap Two Numbers without using Temp Variable in Java? (Trick)
  • How to calculate factorial using recursion in Java? (solution)
  • How to remove duplicates from array without using Collection API? (Solution)
  • Write a Program to Check if a number is Power of Two or not? (Answer)
  • How to find first non repeated characters from String in Java? (solution)
  • Write a program to check if a number is Prime or not? (Solution)
  • How to calculate Sum of Digits of a number in Java? (Solution)
  • Write a method to count occurrences of  a character in String? (Solution)
  • Write a method to remove duplicates from ArrayList in Java? (Solution)
  • Write a program to check if a number is Palindrome or not? (Solution)
  • Howto solve Producer Consumer Problem in Java. (Solution)
  • How to find Fibonacci Series of a Given Number? (Solution)
  • How to reverse String in Java without using API methods? (Solution)
  • Write a method to check if two String are Anagram of each other? (Solution)
  • How to check if a number is Armstrong number or not? (Solution)
  • Write a program to check if Array contains duplicate number or not? (Solution)


6 comments :

R Seiler said...

Your removeRecursive() runs in memory troubles if you have a long string with many occurences of the unwanted char as it generates a new String each time... Not a good way to cope with the task, I think.

mani said...

Another way of doing iteratively is just using string.length() function.

Anonymous said...

@R Seiler Indeed recursion and StackOverflowError often go hand-in-hand.Especially since (default) stack size is a fraction of (default) heap size.
But the author is making a huge mistake from the start: applying recursion should be a means to get something done, not the goal by itself!!

Quontra Solu said...

Hi,

Can you please explain with another logic

Milan said...

To improve your solution I would change the last line in the recursive function as follows
return word.substring(0, index) + removeRecursive(word.substring(index +1, word.length()), ch);

However, it is important to note that Recursive function would take much more space then the iterative as it will generate lots of new strings. I don't see this solution solving the interviewer's goal to reduce the O(n) space complexity

Vikas Kumar Singh said...

String input="vikas";
char removChar='k';
String result="";
for(int i=0;i<input.length();i++){
if(input.charAt(i)!=removChar){
result+=input.charAt(i);
}
}
System.out.println(result);

Post a Comment