Remove Character at a Specified Position in Java



In this article, we will learn to remove a character from a string at a specified position using Java. We will use the substring() method to achieve this by splitting the string before and after the character we want to remove, then combining the two parts

Problem Statement

Write a program in Java to remove a character at a specified position.

Input

The Haunting of Hill House!

Output

String after removing a character: The Hauting of Hill House!

Steps to remove a character at a specified position

Following are the steps to remove a character at a specified position ?

  • Define the string and specify the position of the character to be removed.
  • Use the substring() method to get the parts of the string before and after the specified position.
  • Combine both parts to get the final string.
  • Print the modified string.

Java program to remove a character at a specified position

The following is the complete example with output ?

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!

Code Explanation

To remove a character at a specified position, we 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);
Updated on: 2024-09-16T23:26:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements