0
0
JavaHow-ToBeginner · 3 min read

How to Remove Character from String in Java - Simple Guide

In Java, you can remove a character from a string by using the replace() method, which replaces the character with an empty string. For example, str.replace('a', "") removes all 'a' characters from str. Another way is to use StringBuilder to build a new string without the unwanted character.
📐

Syntax

The most common way to remove a character from a string is using the replace() method:

  • String newStr = originalStr.replace(charToRemove, "");

Here, charToRemove is the character you want to remove, and replacing it with an empty string "" effectively deletes it.

java
String newStr = originalStr.replace('a', '');
💻

Example

This example shows how to remove all occurrences of the character 'e' from a string using replace(). It prints the original and the modified string.

java
public class RemoveCharExample {
    public static void main(String[] args) {
        String original = "Hello, welcome to Java!";
        String modified = original.replace('e', '');
        System.out.println("Original: " + original);
        System.out.println("Modified: " + modified);
    }
}
Output
Original: Hello, welcome to Java! Modified: Hllo, wlcom to Java!
⚠️

Common Pitfalls

One common mistake is trying to remove a character by assigning '' (empty char) which is invalid in Java. Also, replace() removes all occurrences, so if you want to remove only the first occurrence, you need a different approach.

Another pitfall is forgetting that strings are immutable in Java, so you must assign the result of replace() to a new string or the same variable.

java
/* Wrong way - causes error */
// String newStr = originalStr.replace('a', ''); // Correct
// String newStr = originalStr.replace('a', ''); // Correct

/* To remove only first occurrence */
String original = "banana";
String newStr = original.replaceFirst("a", "");
System.out.println(newStr); // prints "bnana"
Output
bnana
📊

Quick Reference

MethodDescriptionExample
replace(char oldChar, char newChar)Replaces all occurrences of a characterstr.replace('a', "")
replaceFirst(String regex, String replacement)Replaces first occurrence matching regexstr.replaceFirst("a", "")
Using StringBuilderBuilds a new string skipping unwanted charsUse loop to append chars except target

Key Takeaways

Use replace() to remove all occurrences of a character by replacing it with an empty string.
Strings are immutable in Java; always assign the result of replace() to a variable.
To remove only the first occurrence, use replaceFirst() with a regex.
Avoid using empty char '' as it is invalid; use empty string "" instead.
For more control, use StringBuilder to build a string without the unwanted character.