• Courses
  • Tutorials
  • DSA
  • Data Science
  • Web Tech
August 06, 2022 |24.3K Views

Java Program to Remove First and Last Character of a String

Description
Discussion

In this video, we will learn the Java programs to remove the first and last character of a string. 

We see three different methods for removing the first and last character of a string in JAVA: 

1. String.Substring(): The String.Substring() method returns a new string that is a substring of the original string. 

2. StringBuilder deleteCharAt(): The deleteCharAt(int index) method of StringBuilder class remove the character at the given index from String contained by StringBuilder. This method takes the index as a parameter which represents the index of char we want to remove and returns the remaining String as StringBuilder Object. This StringBuilder is shortened by one char after the application of this method. 

3. Stringbuffer.delete(): The java.lang.StringBuffer.delete() is an inbuilt method in Java that is used to remove or delete the characters in a substring of this sequence. The substring starts at a specified index start_point and extends to the character at the index end_point.

Examples: 
1. Input string = “GeeksforGeeks” 
Output string: eeksforGeek 

Here, the first character of the given string is ‘G’ and the last character of the given string is ‘s’. After removing the first and last character of a string, the string becomes “eeksForGeek”. 

2. Input string = “Java Program” 
Output: ava Progra 

Here, the first character of the given string is ‘J’ and the last character of the given string is ‘m’. After removing the first and last character of a string, the string becomes “ava Progra”. 

Program to Remove First & Last Character of a String:
https://www.geeksforgeeks.org/remove-first-and-last-character-of-a-string-in-java/