Given string str, the task is to write 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 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”. Input: str = “Java” Output: av Explanation: The first character of the given string is ‘J’ and the last character of the given string is ‘a’. After removing first and last character of a string, the string becomes “av”.
Method 1: Using String.substring() method
Below is the implementation of the above approach:
// Java program to remove the first and // the last character of a string class GFG { // Function to remove the first and // the last character of a string public static String removeFirstandLast(String str) { // Removing first and last character // of a string using substring() method str = str.substring(1, str.length() - 1); // Return the modified string return str; } // Driver Code public static void main(String args[]) { // Given String str String str = "GeeksForGeeks"; // Print the modified string System.out.print( removeFirstandLast(str)); } }
Output:
eeksForGeek
Method 2: Using StringBuilder.deleteCharAt() method
Below is the implementation of the above approach:
// Java program to remove the first and // the last character of a string class GFG { // Function to remove the first and // the last character of a string public static String removeFirstandLast(String str) { // Creating a StringBuilder object StringBuilder sb = new StringBuilder(str); // Removing the last character // of a string sb.deleteCharAt(str.length() - 1); // Removing the first character // of a string sb.deleteCharAt(0); // Converting StringBuilder into a string // and return the modified string return sb.toString(); } // Driver Code public static void main(String args[]) { // Given String str String str = "GeeksForGeeks"; // Print the modified string System.out.println( removeFirstandLast(str)); } }
Output:
eeksForGeek
Method 3: Using StringBuffer.delete() method
Below is the implementation of the above approach:
// Java program to remove the first and // the last character of a string class GFG { // Function to remove the first and // the last character of a string public static String removeFirstandLast(String str) { // Creating a StringBuffer object StringBuffer sb = new StringBuffer(str); // Removing the last character // of a string sb.delete(str.length() - 1, str.length()); // Removing the first character // of a string sb.delete(0, 1); // Converting StringBuffer into // string & return modified string return sb.toString(); } // Driver Code public static void main(String args[]) { // Given String str String str = "GeeksForGeeks"; // Print the modified string System.out.println( removeFirstandLast(str)); } }
Output:
eeksForGeek