Friday, March 11, 2016

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 which 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 character from String in Java. In the last article, I have showed 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 interview point of view. Until JDK 1.7, it had a bug which 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 first character, reference of 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 book like Java Programming Interview exposed can be really beneficial. You will cover lot more topics in very short time, which are critical from interview point of view.

How to remove first and last character of String in Java

Using substring() to remove first and 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 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.

"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 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

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());


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.

Further Learning
Java Fundamentals: The Java Language by Jim Wilson
Algorithms and Data Structures - Part 1 and 2
What's New in Java 8
What's New in Java 9 By Sander Mak


Amit Pundeer said...

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

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

Do rectify.

Javin Paul said...

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

Amit Pundeer said...

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..

Javin Paul said...

@Amit, thanks again, corrected.

Deepak Kumar said...

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

Post a Comment