Remove characters from the end of a string in Kotlin
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:
|
1 2 3 4 5 6 7 8 9 |
fun removeLastNchars(str: String, n: Int): String { return str.substring(0, str.length - n) } fun main() { val str = "Main.kt" val n = 3 println(removeLastNchars(str, n)) // Main } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeLastNchars(str: String?, n: Int): String? { return if (str == null || str.length < n) { str } else str.substring(0, str.length - n) } fun main() { val str = "Main.kt" val n = 3 println(removeLastNchars(str, n)) // Main } |
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.
|
1 2 3 4 5 6 7 8 |
fun removeLastChar(str: String?): String? { return str?.replaceFirst(".$".toRegex(), "") } fun main() { val str = "User1" println(removeLastChar(str)) // User } |
That’s all about removing characters from the end of a string in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)