In this tutorial, you shall learn how to remove last N characters from a given string in Kotlin, using String.dropLast() function, with examples.

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.

Examples

ADVERTISEMENT

1. Remove last three characters from 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

2. Number of characters to be removed > length of given string

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.