Remove a given character from String

In this article, you will learn how to remove a given character from a string in Java. To remove a given character from a String in Java, you can use the replace method. The replace method replaces all occurrences of the specified character with an empty string.

Here are a few different solutions in Java for it:

1. Using replace method

In this program, the removeCharacter method takes the input String and the char to remove as arguments. It uses the replace method on the input string, passing the character to remove as the first argument and an empty string "" as the second argument. The replace method replaces all occurrences of the given character with an empty string, effectively removing them.

package com.javacodepoint.string;

public class RemoveCharacterFromString {
	
	public static String removeCharacter(String input, char charToRemove) {
		if (input == null || input.isEmpty()) {
			return input; // If the input is null or empty, return as it is.
		}

		// Use the replace method to remove all occurrences of the given character
		String result = input.replace(String.valueOf(charToRemove), "");

		return result;
	}

	public static void main(String[] args) {
		String inputStr = "Hello, World!";
		char charToRemove = 'l';

		String withoutCharacter = removeCharacter(inputStr, charToRemove);

		System.out.println("Original String: " + inputStr);
		System.out.println("String without '" + charToRemove + "': " + withoutCharacter);
	}
}

OUTPUT:

Original String: Hello, World!
String without ‘l’: Heo, Word!

2. Using StringBuilder

In this solution, we use a StringBuilder to build the resulting string. We iterate through each character of the input string, and if the character is not the one we want to remove, we append it to the StringBuilder. This way, the resulting string will contain all characters except the specified one.

package com.javacodepoint.string;

public class RemoveCharacterFromString2 {

	public static String removeCharacter(String input, char charToRemove) {
		if (input == null || input.isEmpty()) {
			return input; // If the input is null or empty, return as it is.
		}

		StringBuilder result = new StringBuilder();
		for (char c : input.toCharArray()) {
			if (c != charToRemove) {
				result.append(c);
			}
		}

		return result.toString();
	}

	public static void main(String[] args) {
		String str = "javacodepoint.com";
		char charToRemove = 'a';

		String withoutCharacter = removeCharacter(str, charToRemove);

		System.out.println("Original String: " + str);
		System.out.println("String without '" + charToRemove + "': " + withoutCharacter);
	}
}

OUTPUT:

Original String: javacodepoint.com
String without ‘a’: jvcodepoint.com

Learn also: Remove all Duplicates from a given String.

Java logical programs list


Java Basic Programs

Java Programs based on the Collection Framework

Leave a Reply

Your email address will not be published. Required fields are marked *