How to remove a particular character from a string in Java?

In this tutorial, we’ll discuss removing a particular character from a string in Java. Consider a user passes an input string and we know the contents of the string., so we try to eliminate a particular character from the string. So how do we do?

For this let us consider one of the built-in methods in java, the deletecharAt() method…

Remove particular character from string: deletecharAt() method

The Java.lang.StringBuffer.deleteCharAt() is a built-in Java method that removes the char at the specified position and results in the reduction of the length of the string by 1.
Let us see the syntax,

Syntax:

public StringBuffer deleteCharAt(int index)

Here, public is an access modifier that may be ignored. The index position of the character is passed as the parameter.

Let us see an example,

import java.lang.*; 
  
public class removechar { 
  
    public static void main(String[] args) 
    { 
  
        StringBuffer b = new StringBuffer("Hello"); 
        System.out.println("String buffer before deletion = " +b); 
  
        // Deleting the character at indexpoint 3 
        b.deleteCharAt(3); 
        System.out.println("After deletion new StringBuffer = " + b); 
    } 
}

Output:

Helo

In the above example, we are deleting the character at index position 3.The string length is decreased by 1, and the java.lang.StringBuffer class is included.
Note that the 3rd index position is ‘l’ because indexing starts from 0.

import java.lang.*; 
  
public class removechar { 
  
    public static void main(String[] args) 
    { 
  
        StringBuffer b = new StringBuffer("Hello"); 
        System.out.println("String buffer before deletion = " +b); 
  
        // Deleting the character at indexpoint 0 
        b.deleteCharAt(0); 
        System.out.println("After deletion new StringBuffer = " + b); 
    } 
}

Output:

ello

Therefore the above Java method helps to remove a particular character from a string. There are also other methods apart from this.
You may also read…

 

Leave a Reply

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