Kotlin adds a lot of extension methods to the String class. For example we can use the take method to get a certain number of characters from the start of a string value. With the drop method where we remove a given number of characters from the start of the string to get a new string. We can also take and drop a certain number of characters from the end of a string using the methods takeLast and dropLast.

Instead of using the number of characters we want to take or drop we can also use a condition defined with a predicate lambda function. We take or drop characters as long as the lambda returns true. The names of the methods for taking characters are takeWhile and takeLastWhile and for dropping characters dropWhile and dropLastWhile.

In the following example we use different methods to take and drop characters from a string value to get a new string value:

val s = "Kotlin kandy!"

// Take the first 6 characters.
assert(s.take(6) == "Kotlin")

// Take the last 6 characters.
assert(s.takeLast(6) == "kandy!")

// Take characters until lowercase k is encountered.
assert(s.takeWhile { it != 'k'} == "Kotlin ")

// Take characters from the end of the string
// to the beginning until a space is encountered.
assert(s.takeLastWhile { it != ' '} == "kandy!")


// Drop the first 7 characters.
assert(s.drop(7) == "kandy!")

// Drop the last 7 characters.
assert(s.dropLast(7) == "Kotlin")

// Drop characters until a lowercase k is encountered.
assert(s.dropWhile { it != 'k'} == "kandy!")

// Drop characters starting at the end of the string
// until a space is encountered.
assert(s.dropLastWhile { it != ' '} == "Kotlin ")

Written with Kotlin 1.7.20.

shadow-left