Kotlin – Remove Last N Characters from String

To remove last N characters from a String in Kotlin, use String.dropLast() method.

Given a string str1, and if we would like to remove last n characters from this string str1, call dropLast() method on string str1 and pass the integer n as argument to the method as shown below.

str1.dropLast(n)

dropLast() method returns a new string with the last n characters removed from the given string.

Example 1 – Remove Last N Characters in String

In this example, we will take a string in str1, and drop the last 3 characters from the string str1.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val n = 3
    val result = str1.dropLast(n)
    println("Original String  : " + str1)
    println("Resulting String : " + result)
}

Output

Original String  : abcdefg
Resulting String : abcd

Example 2 – N > String Length

If the value of n is greater than the original string length, then dropLast() method returns an empty string.

Kotlin Program

fun main(args: Array<String>) {
    val str1 = "abcdefg"
    val n = 10
    val result = str1.dropLast(n)
    println("Original String  : " + str1)
    println("Resulting String : " + result)
}

Output

Original String  : abcdefg
Resulting String :

Conclusion

In this Kotlin Tutorial, we learned how to remove last N characters from a given string using String.drop() method, with the help of Kotlin example programs.