This post will discuss how to remove an extra delimiter at the end of StringBuilder class in Java.

An extra delimiter gets added while looping through a collection and appending each element to a StringBuilder object separated by a delimiter. Consider the following code that will add an extra delimiter at the end.

Download  Run Code

 
This is a very common problem which every Java developer must have faced at least once in his lifetime. Let’s discuss a few methods to address this problem:

1. Using for loop

This method still loops through the collection but does that in a clever way. Instead of appending the delimiter, it appends the delimiter at the starting of each value and uses the empty string as a delimiter for the first value of the collection. This way, no extra delimiter is added at the end.

Download  Run Code

2. Using a variable

Another option is to use a variable to keep track of the collection size and appends the delimiter only if we are not at the last element in the list. This way, we avoid adding an extra delimiter at the end.

Download  Run Code

3. Using StringJoiner Class

In Java 8 and above, we can use StringJoiner class in place of StringBuilder, which takes a delimiter and construct a sequence of values separated by the delimiter. This class automatically handles the last delimiter and does not add the extra delimiter at the end.

Download  Run Code

4. Using setLength() or deleteCharAt() methods

The following solutions allows the loop to add the extra character at the end of StringBuilder, but removes it using utility methods provided by StringBuilder class:

⮚ Using setLength() method

The setLength() method allows us to set the length of a StringBuilder object. We can set the length of the StringBuilder to one less than its current length, which will effectively remove the last character.

Download  Run Code

⮚ Using deleteCharAt() method

The deleteCharAt() method allows us to remove a character from a StringBuilder object by specifying its index. We can use sb.length() - 1 as the index to remove the last character.

Download  Run Code

That’s all about removing the extra delimiter at the end of StringBuilder in Java.

 
Related Post:

Delete extra separator from the end of String in Java