Java Program to remove a character at a specified position

Java 8Object Oriented ProgrammingProgramming

To remove a character at a specified position, use the following logic −

Let’s say the following is our string.

String str = "The Haunting of Hill House!";

We want to remove a character at position 7. For that, use the below logic.

// removing character at position 7
int pos = 7;
String res = str.substring(0, pos) + str.substring(pos + 1);

The following is the complete example with output.

Example

 Live Demo

public class Demo {
    public static void main(String[] args) {
       String str = "The Haunting of Hill House!";
       System.out.println("String: "+str);
       // removing character at position 7
       int pos = 7;
       String res = str.substring(0, pos) + str.substring(pos + 1);
       System.out.println("String after removing a character: "+res);
    }
}

Output

String: The Haunting of Hill House!
String after removing a character: The Hauting of Hill House!
raja
Published on 12-Dec-2018 07:07:56
Advertisements