Kotlin .dropLast()
Published Dec 6, 2023
Contribute to Docs
The Kotlin method, .dropLast() removes one or n number of characters from the end of the string. Here, n is a positive integer given as a parameter to the method. This method does not modify the original list, it creates and returns a new list.
Syntax
fun String.dropLast(n: Int): String
- The parameter
nis the number of characters to be removed from the string.
Note:
IllegalArguementExceptionerror thrown ifnis a negative number. A negative number of characters can not be removed.
Example
The example below creates a string, string, then uses the .dropLast() method to return a string with the last five characters removed.
fun main() {val string = "Example String"println(string.dropLast(1))println(string.dropLast(5))}
The output will look like the following:
Example StrinExample S
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Kotlin on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Kotlin, the expressive, open-source programming language developed by JetBrains.
- Beginner Friendly.9 hours