Remove a Character from String in Java

Need to remove a character from String in Java? 

You can do that by converting the String to a StringBuilder class and using the deleteCharAt() method that removes the character at a specified position.

Example

class Test {

  public static void main(String[] args) {
    String str = "Learn Java";

    str = new StringBuilder(str).deleteCharAt(5).toString();

    System.out.println(str);
  }
}
Output: LearnJava
 
There is also a way using the substring() method like in the following example:
class Test {

  public static void main(String[] args) {
    String str = "Learn Java";

    // remove char at index 5
    str = str.substring(0, 5) + str.substring(6);

    System.out.println(str);
  }
}
Output: LearnJava
 
If you don’t know the index of a char you want to remove, you can find it using the indexOf() method:
class Test {

  public static void main(String[] args) {
    String str = "Learn Java";

    int index = str.indexOf("n");

    System.out.println(str.substring(0, index) + str.substring(index + 1));
  }
}
Output: Lear Java
 
That’s it!

Leave a Reply

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