Saturday, July 2, 2022

How to Remove First and Last Character of String in Java - Example Tutorial

You can use the substring() method of java.lang.String class to remove the first or last character of String in Java. The substring() method is overloaded and provides a couple of versions that allows you to remove a character from any position in Java. Alternatively, you can convert String to StringBuffer or StringBuilder and then use its remove() method to remove the first or last character. Both StringBuffer and StringBuilder provides a convenient deleteCharAt(int index) method which removes a character from the corresponding index. You can use this method to remove both first and last characters from String in Java.

In the last article, I have shown you how to get the first and last character from String and today I will teach you how to remove the first and last character of String in Java. Let's see a couple of examples and how you can use these two techniques to solve this problem.

The substring() method is pretty special in Java, at least from the interview point of view. Until JDK 1.7, it had a bug that keeps the reference to the original String whenever you ask for a substring.

This effectively means if you have a very long String and you just need the first character, reference of the original String is retained even though it wasn't required. This is known as a memory leak in Java and this prompted questions like how substring() method works in Java. If you are running on JDK 1.6, it's still one of the useful detail to know about.
=
By the way, if you are preparing for Java programming interviews then always make sure that you have a solid understanding of various String concepts e.g. String pool, garbage collection, regular expression, etc. If you are running short of time then referring to these Java Interview courses can be really beneficial. You will cover a lot more topics in a very short time, which are critical from the interview point of view.






Using substring() to remove first and the last character

The java.lang.String class defines two substring method, substring(int beginIndex) and substring(int beginIndex, int endIndex). The first version will create a substring starting from the beginIndex and include all subsequent characters. 

So, if you want to remove the first character of String, just create a substring from the second character. Since index starts from zero in String, "text".substring(1) is equivalent to deleting the first character. 

This is exactly what I have done in the first example of our sample program.
In order to remove the last character, I have used the second version of substring() method, which takes both a start and end index. 

An important point to remember is that beginIndex is inclusive but endIndex is the exclusive. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus, the length of the substring is endIndex-beginIndex.
Examples:

"hamburger".substring(3, 9) returns "burger"
"smiles".substring(1, 5) returns "mile"

You can use this method to remove the last character by specifying an index which is less than 1 of length of String as shown below:

"hamburger".substring(0, 8) returns "hamburge"

You can also see these 5 examples of the substring to understand how these two substring methods works.


Here are some important points about the substring method in Java for your quick reference:




Using deleteCharAt() to delete first or last character

Another way to take out the first and last character from String is by using StringBuffer and StringBuilder class. If you remember those classes are added in API to facilitate String manipulation.

So, if you are deleting characters from String, the best way is to first convert String to StringBuilder and then use either delete() or deleteCharAt(int index) method to remove characters.

You can use deleteCharAt(0) to remove the first character and deleteCharAt(length - 1) to remove the last character from String in Java, as shown in our second example.




Java Program to remove first and last character

Here is a sample program to demonstrate how to remove the first and last character from String in Java. This program will explain the approaches we have discussed above. If you have any doubt then check the online Java documentation.


public class SubStringDemo{

public static void main(String args[]) {

// 1st example: You can use substring() method to remove first
// and the last character from String in Java.

String text = "iMac";
String withoutFirstCharacter = text.substring(1); // index starts at zero
String withoutLastCharacter = text.substring(0, text.length() - 1);

System.out.println("Using SubString() method: ");
System.out.println("input string: " + text);
System.out.println("without first character: " + withoutFirstCharacter);
System.out.println("without last character: " + withoutLastCharacter);


// 2nd Example - You can use StringBuffer or StringBuilder to remove
// first or last character from String in Java
String iStore = "iCloud";

// converting String to StringBuilder
StringBuilder builder = new StringBuilder(iStore); 

// removing first character
builder.deleteCharAt(0);

System.out.println("Using StringBuilder deleteCharAt() method: ");
System.out.println("input string: " + iStore);
System.out.println("String after removing first character: " 
                    + builder.toString());

// creating another StringBuilder
builder = new StringBuilder(iStore);

// removing last character from String
builder.deleteCharAt(iStore.length() - 1);
System.out.println("String after removing last character: " 
   + builder.toString());
}

}

Output
Using SubString() method: 
input string: iMac
without first character: Mac
without last character: iMa

Using StringBuilder deleteCharAt() method: 
input string: iCloud
String after removing the first character: Cloud
String after removing the last character: iClou


That's all about how to remove the first character or last character or both from a String in Java. As I said, you can either use substring() method or deleteCharAt() method of StringBuilder/StringBuffer to remove the first or last character.  

Since String is immutable in Java and cannot be changed or modified once created, substring() method will return new String without first or last character and you need to store the result in a variable before you can use.

On the other hand, since StringBuilder and StringBuffer are a mutable object, the character is removed from the object itself. That's why I have used separate StringBuilder instance to demonstrate removing the first character and deleting the last character.


Other Java String tutorials for further Reading
  • How to compare two String objects in Java? (solution)
  • 35 Java String concepts interview questions (questions)
  • How to reverse String in Java using iteration and recursion? (solution)
  • How to convert Double to String in Java? (answer)
  • When to use the intern() method in Java? (answer)
  • How to convert byte array to Hex String in Java? (answer)
  • How to use intern() method of String in Java? (intern method)
  • How to prepare Java Interviews? (topics and resources)

6 comments:

  1. Hello,
    You have missed to remove from the letter 'r' from the below statement.

    "hamburger".substring(0, 8) returns "hamburger"

    Do rectify.

    ReplyDelete
  2. Thanks Amit, nice spotting. That statement should remove last character "r" and return "hamburge"

    ReplyDelete
  3. Inside:
    Using deleteCharAt() to delete first or last character

    In second paragraph, the deleteCharAt(1) prototype to remove last index is wrong. Please rectify that.

    It should be,
    deleteCharAt(string.length() - 1 ) to remove the last character..

    ReplyDelete
  4. @Amit, thanks again, corrected.

    ReplyDelete
  5. to be more specific,if the start<0 OR start>end, the exception is "java.lang.StringIndexOutOfBoundsException".

    ReplyDelete