This post will discuss how to remove the redundant delimiter from the end of a string in Kotlin.

An extra delimiter might get added while iterating over a list and creating a delimited string. For example, the following code appends a redundant comma at the end of the string.

Download Code

 
There are several ways to fix this, as covered below:

1. Using substring() function

A simple solution is to use the substring() function to get a substring containing all the characters of the given string except the last.

Download Code

2. Using joinToString() function

In Kotlin, we can avoid looping over the list to get the delimited string. The idea is to invoke the joinToString() function, which returns a new string with the elements of the list joined together using the specified delimiter.

Download Code

Output:

A,B,C

3. Using replaceFirst() function

To remove the last character from the end of a string, we can either use the replace() or the replaceFirst() function that accepts a regular expression. The following solution uses the regex .$ to match with the last character. This works since . matches with any single character (except the line terminating character), and $ matches the position right after the string’s end.

Download Code

4. Using StringBuilder

Finally, we can convert the string into a StringBuilder and invoke its deleteCharAt() function to delete the last character. This is demonstrated below:

Download Code

That’s all about removing the redundant delimiter from the end of a string in Kotlin.