Delete extra separator from end of the String in Java

In this post, we will discuss how to delete extra separator from the end of a String that gets added while looping through a Collection and adding each item to a String separated by a separator.


 
For instance, consider below code that will add an extra separator at end of the String.

 

Download   Run Code

 
Above code prints BLACK,GREY,WHITE,. The output has an undesired extra comma in the end. There are many ways to fix this as covered below:

 

1. substring() method

The simplest solution is to use substring() method provided by the String class. Here we simply take substring from the beginning and consider all characters of the string except the last character.

 

Download   Run Code

 

2. Regular Expression

Another solution is to use regex for this. Below solution uses the regex .$. It works as . matches a single character (except newline character) and $ matches position just after the last character of the string.

 

Download   Run Code

 

3. Apache Commons Lang – StringUtils class

 
Another approach is to use StringUtils.chop() method that simply removes the last character from a String. It is by far the most readable solution. It also takes care of null or empty string.

 

Download

 
StringUtils class also provides deleteEnd() method which removes the specified substring if it is at the end of the original string. We can use it as shown below:

 

Download

 
StringUtils substring() method permits the negative indexes which are offset from the end of the string. We can use it as shown below. Here -1 means count back from the end of the String by 1 character.

 

Download

 

4. StringBuilder

The idea here is to convert the string to a StringBuilder and use its deleteCharAt() method to delete character present at the last index. Finally, we convert StringBuilder back to a String.

 

Download   Run Code

 

5. String.join()

In Java 8, we can simply use join() method which is static utility method included in the String class. It returns a new String composed of copies of the elements joined together with a copy of the specified separator.

The advantage of using this approach is that we have completely got rid of the loop.

 

Download   Run Code

Output:

BLACK,GREY,WHITE

 

6. Joiner class from Guava

Similar to String.join() method, Guava provides Joiner class which joins elements of a collection with a separator.

 

Download   Run Code

Output:

BLACK,GREY,WHITE

 
Please note this won’t work if the list contains any null values since Guava doesn’t support nulls. For handling the null values, we can do something like:

 

 

 
Related Post: Remove extra separator at the end of StringBuilder

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz