VOOZH about

URL: https://www.geeksforgeeks.org/dsa/remove-first-and-last-character-of-a-string-in-java/

⇱ Remove first and last character of a string in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Remove first and last character of a string in Java

Last Updated : 15 Jul, 2025

Given a string str, the task is to write the Java Program to remove the first and the last character of the string and print the modified string.

Examples:

Input: str = "GeeksForGeeks"
Output: "eeksForGeek"
Explanation: The first and last characters of the given string are 'G' and 's' respectively. After removing both the characters, the string will be "eeksForGeek".

Input: str = "Java"
Output: "av"
Explanation: The first and last characters of the given string are 'J' and 'a' respectively. After removing both the characters, the string will be "av".

[Approach - 1] Using string.substring() Method - O(n) Time and O(1) Space

The idea is to use the String.substring() method of string class to remove the first and the last character of a string.

  • This method accepts two parameters, the start and end index of the substring, and extracts the substring from index start to end - 1.
  • We are required to remove the characters at index 0 and n - 1, thus we will call the method with parameters 1 and n - 1.

Output
eeksForGeek

[Approach - 2] Using StringBuilder.deleteChatAt() Method - O(n) Time and O(n) Space

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. To do so, firstly create a StringBuilder object sb for the given string. Remove the first and last character using sb.deleteCharAt(0) and sb.deleteCharAt(str.length() - 1) respectively.


Output
eeksForGeek

[Approach - 3] Using StringBuffer.delete() Method - O(n) Time and O(n) Space

The idea is to use the delete() method of StringBuffer class to remove first and the last character of a string.

  • To do so, firstly create the StringBuffer object for the given string. This method accepts two parameters, the start and end index of the string to delete.
  • Remove the first and the last character using sb.delete(0, 1) and sb.delete(str.length() - 1, str.length()) respectively.

Output
eeksForGeek

[Approach - 4] Using Regular Expression - O(n) Time and O(1) Space

The idea is used to Regular Expression for removing the first and last character from the string.

  • To do so, first pass the regex in the pattern.compile() method. Then use pattern object with pattern.matcher() method.
  • At last, remove the first and last character of string using Regex store the result in result variable

Output
eeksforGeek


Comment