
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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);
Advertisements