Java Remove Character from String With Examples

Sometimes we have to remove character from String in java program. But java String class doesn’t have remove() method. So how would you achieve this?

Java Remove Character from String

If you notice String class, we have replace() methods with different variations. Let’s see what all overloaded replace() methods String class has;

  1. replace(char oldChar, char newChar): Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
  2. replace(CharSequence target, CharSequence replacement): Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
  3. replaceFirst(String regex, String replacement): Replaces the first substring of this string that matches the given regular expression with the given replacement.
  4. replaceAll(String regex, String replacement): Replaces each substring of this string that matches the given regular expression with the given replacement.

So can we use replace('x','');? If you will try this, you will get compiler error as Invalid character constant. So we will have to use other replace methods that take string, because we can specify “” as empty string to be replaced.

Java String Remove Character Example

Below code snippet shows how to remove all occurrences of a character from the given string.

Java Remove substring from String

Let’s see how to remove first occurrence of “ab” from the String.

Notice that replaceAll and replaceFirst methods first argument is a regular expression, we can use it to remove a pattern from string. Below code snippet will remove all small case letters from the string.

Java Remove Spaces from String

Java Remove Last Character from String

There is no method to replace or remove last character from string, but we can do it using string substring method.

Java String Remove Character and String Example

Here is the complete java class for the examples shown above.

Output produced by above program is:

That’s all for removing character or substring from string in java program.

By admin

Leave a Reply