How to Remove a Particular Character from a String in Java



In Java, when deleting a certain character by its index position from a string, the method modifies the string that contains the specified character. This is useful in the string manipulating task when certain parts must be deleted. The following are the methods in Java to remove a particular character from a string

  • Using the substring method

  • Using the StringBuilder class

Using the substring method

The substring method extracts parts of a string. In this way, we split the string into two parts and excluded the character at the given index. This allows us to remove the character by concatenating the other parts.

Example

The following example shows how to remove a character from a particular position from a string with the help of the removeCharAt(string, position) method

public class Main {
   public static void main(String args[]) {
      String str = "this is Java";
      System.out.println(removeCharAt(str, 3));
   }
   public static String removeCharAt(String s, int pos) {
      return s.substring(0, pos) + s.substring(pos + 1);
   }
}

Output

thi is Java

Using the StringBuilder class

The StringBuilder class is an easy-to-modify class for strings. Basically, it uses the deleteCharAt method to delete a character at a particular index directly.

Example

The following example shows how to remove a particular character from a string using the StringBuilder Class

public class Main {
   public static void main(String args[]) {
      String str = "this is Java";
      System.out.println(removeCharWithStringBuilder(str, 3)); // Removes character at index 3
   }

   public static String removeCharWithStringBuilder(String s, int pos) {
      StringBuilder sb = new StringBuilder(s); // Creates a StringBuilder object
      sb.deleteCharAt(pos); // Deletes the character at the specified index
      return sb.toString(); // Converts StringBuilder back to String
   }
}

Output

thi is Java
java_strings.htm