![]() |
VOOZH | about |
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".
Table of Content
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.
eeksForGeek
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.
eeksForGeek
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.
eeksForGeek
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
eeksforGeek