- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java program for removing n-th character from a string
The n-th character from a string can be removed using the substring() function. An example of this is given as follows −
String = Happy The 3rd character is removed = Hapy
A program that demonstrates this is given as follows −
Example
public class Example { public static void main(String args[]) { String str = "Apple"; System.out.println("Original string: " + str ); System.out.println("String with 4th character removed: " + removeChar(str, 4)); } public static String removeChar(String str, int n) { return str.substring(0, n-1) + str.substring(n); } }
Output
Original string: Apple String with 4th character removed: Appe
Now let us understand the above program.
The function removeChar() removes the nth character from the given string. This is done by using the substring of function. Then the remaining string is returned. The code snippet that demonstrates this is given as follows −
public static String removeChar(String str, int n) { return str.substring(0, n-1) + str.substring(n); }
In the function main(), the string str is defined. Then the original string is displayed and the modified string is displayed by calling removeChar(). The code snippet that demonstrates this is given as follows −
public static void main(String args[]) { String str = "Apple"; System.out.println("Original string: " + str ); System.out.println("String with 4th character removed: " + removeChar(str, 4)); }
Advertisements