Java program for removing n-th character from a string

Java 8Object Oriented ProgrammingProgramming

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

Live Demo

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));
}
raja
Published on 05-Dec-2018 13:53:40
Advertisements