This article explores different ways to remove characters from the end of a string in Kotlin.

Since strings are immutable in Kotlin, we can’t remove characters from it. However, we can create a new string instance with the last n characters removed.

1. Using substring() function

The standard approach is to use the substring() function to get a substring starting from the beginning of the string, with the last n characters excluded. This would translate to a simple code below:

Download Code

 
We should place the range check before the substring() function, otherwise the string index out of range exception is thrown if the starting or the ending index is out of bounds.

Download Code

2. Using replaceFirst() function

To remove the last character from the end of a string, we can use the replaceFirst() or the replace() function. Both these functions accept a regular expression for matching. Its usage is demonstrated below, using the regular expression .$ that matches the last character.

Download Code

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