Removing the Last Character from a Java StringBuilder

06 May 2023 Balmiki Mandal 0 Core Java

How to Remove the Last Character of a Java StringBuilder

A Java StringBuilder object is an modifiable string for building strings. It's an efficient way of appending strings together through its append() method, which appends a given set of characters to the end of the existing string and makes a copy each time it does so. While append() is the most commonly used StringBuilder method, there are several ways to remove the last character from a StringBuilder, depending on your needs.

Using the deleteCharAt() Method

The deleteCharAt() method is the quickest and simplest way to delete the last character of a StringBuilder. It takes an index as its parameter and deletes the character at that index. Since a StringBuilder's length is always one greater than the index of its last character, all you need to do is pass in the StringBuilder’s length minus one.

StringBuilder sb = new StringBuilder("Hello World!");
sb.deleteCharAt(sb.length() - 1); // "Hello World"

Using setLength() Method

Another way to remove the last character from a StringBuilder is to use the setLength() method. This method takes an integer as its parameter, which will be the new length of the StringBuilder. Pass in the StringBuilder’s current length minus one and it will shorten the StringBuilder by one character.

StringBuilder sb = new StringBuilder("Hello World!");
sb.setLength(sb.length() - 1); // "Hello World"

Using substring() Method

Finally, if you need to extract the substring without the last character, you can use the substring() method, which takes two arguments: the starting index of the substring and the ending index. This method returns the substring between the two indexes (not including the character at the ending index) and doesn’t modify the original StringBuilder. The end index should be the StringBuilder’s length minus one.

StringBuilder sb = new StringBuilder("Hello World!");
String result = sb.substring(0, sb.length() - 1); // "Hello World"

These are just a few ways to remove the last character from a Java StringBuilder. Depending on your needs and preferences, you can select the best option for your project!

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.