Java 8 – Remove input-ted Character from a given String

In this article, we will discuss how to remove specific character from a given String using different approaches

Remove Character from a given String :

  • Using Java 8 Stream & Collectors
  • Using String.replaceAll(old, new) method
  • Using Iterative approach

1. Remove Character using Java 8’s Stream & Collectors

  • For the given String, get Stream using Stream.chars() method
  • Iterate through character Stream and do the following,
  • Return the result and print to console

RemoveCharacterUsingJava8Stream.java

package in.bench.resources.remove.characters;

import java.util.stream.Collectors;

public class RemoveCharacterUsingJava8Stream {

	// main() method
	public static void main(String[] args) {

		// sample String
		String str = "BeEnchReEsources.NeEt";


		// character to be removed
		char ch = 'e';


		// print to console
		System.out.println("Sample input String : \n" + str);
		System.out.println("\nCharacter to be removed : \n" + ch);


		// invoke method
		String result = removeCharacter(str, ch);


		// print to console
		System.out.println("\nResult : \n" + result);
	}


	/**
	 * This method is used to remove passed character from the given String
	 * 
	 * @param str
	 * @param ch
	 * @return
	 */
	private static String removeCharacter(String str, char ch) {

		// check for null & empty
		if(null == str || str.isEmpty() || str.length() == 0) {

			// throw IllegalArgumentException
			throw new IllegalArgumentException("Input String can't be null");
		}


		// return
		return str // original string or source
				.chars() // get Stream
				.filter(c -> ch != c) // filter out matching chars
				.mapToObj(c -> String.valueOf((char) c)) // convert to char
				.collect(Collectors.joining()); // collect to String
	}
}

Output:

Sample input String : 
BeEnchReEsources.NeEt

Character to be removed : 
e

Result : 
BEnchREsourcs.NEt

2. Remove Character using String.replaceAll() method

  • This is the simplest approach where we will replace all specific character with empty string eventually replacing all characters from the given String
  • Return the result and print to console

RemoveCharacterUsingReplaceAllMethod.java

package in.bench.resources.remove.characters;

public class RemoveCharacterUsingReplaceAllMethod {

	// main() method
	public static void main(String[] args) {

		// sample String
		String str = "BeEnchReEsources.NeEt";


		// character to be removed
		char ch = 'E';


		// print to console
		System.out.println("Sample input String : \n" + str);
		System.out.println("\nCharacter to be removed : \n" + ch);


		// invoke method
		String result = removeCharacter(str, ch);


		// print to console
		System.out.println("\nResult : \n" + result);
	}


	/**
	 * This method is used to remove passed character from the given String
	 * 
	 * @param str
	 * @param ch
	 * @return
	 */
	private static String removeCharacter(String str, char ch) {

		// check for null & empty
		if(null == str || str.isEmpty() || str.length() == 0) {

			// throw IllegalArgumentException
			throw new IllegalArgumentException("Input String can't be null");
		}


		// return
		return str.replaceAll(String.valueOf(ch), "");
	}
}

Output:

Sample input String : 
BeEnchReEsources.NeEt

Character to be removed : 
E

Result : 
BenchResources.Net

3. Remove Character using Iterative approach

  • Convert the given String into char[] array using String.toCharArray() method and then iterate through character[] array using standard for-loop
  • While iterating, compare passed-character with the iterating characters one-by-one for equality inside if-condition,
    • If they’re equal then leave/remove that character from the String
    • Otherwise, append that character into newly created StringBuider object and return the sbd object after converting to String using String.toString() method
  • Return the result and print to console

RemoveCharacterUsingIterativeApproach.java

package in.bench.resources.remove.characters;

public class RemoveCharacterUsingIterativeApproach {

	// main() method
	public static void main(String[] args) {

		// sample String
		String str = "BeEnchReEsources.NeEt";


		// character to be removed
		char ch = 'E';


		// print to console
		System.out.println("Sample input String : \n" + str);
		System.out.println("\nCharacter to be removed : \n" + ch);


		// invoke method
		String result = removeCharacter(str, ch);


		// print to console
		System.out.println("\nResult : \n" + result);
	}


	/**
	 * This method is used to remove passed character from the given String
	 * 
	 * @param str
	 * @param ch
	 * @return
	 */
	private static String removeCharacter(String str, char ch) {

		// local variable
		StringBuilder sbd = new StringBuilder();


		// check for null & empty
		if(null == str || str.isEmpty() || str.length() == 0) {

			// throw IllegalArgumentException
			throw new IllegalArgumentException("Input String can't be null");
		}


		// convert String to char[] array
		char[] chArray = str.toCharArray();


		// iterate through char[] array
		for(int index = 0; index < chArray.length; index++) {

			// check for character equality
			if(ch != chArray[index]) {
				sbd.append(chArray[index]);
			}
		}

		// return
		return sbd.toString();
	}
}

Output:

Sample input String : 
BeEnchReEsources.NeEt

Character to be removed : 
E

Result : 
BenchResources.Net

Happy Coding !!
Happy Learning !!

Java 8 - How to Sort List by java.util.Date in 4 ways ?
Java 8 – Find Second Smallest number in an Arrays or List or Stream ?